station
station

Reputation: 7145

How to autowire this dependency in spring at the time of PostConstruct

I have the below code inside the @PostConstruct block in a spring managed code.


class A {

    private BoogleFeature boogle;

    @PostConstruct
        public void createBoggleClient() {
                SDKPersona.SDKPersonaBuilder sdkBuilder =
                        new AppIdentifier.SDKPersonaBuilder()
                                .setRegistryId(config.getRegistryId())
                                .setRegistrySecret(config.getRegistrySecret())
        
                boggle = new BoggleFeature(sdkBuilder.build());
        }
    }
}

Now i want to not do a boggle = new BoggleFeature(sdkBuilder.build()); and make it as bean and inject it as a deopendency . How can i achieve that.

Upvotes: 2

Views: 271

Answers (2)

Philippe Simo
Philippe Simo

Reputation: 1459

You can use GenericApplicationContext to register the bean dynamically during @PostConstruct this way :

@Component
public class BoogleFactory {

  @Autowired
  private GenericApplicationContext context;

  @PostConstruct
  public void createBoggleClient() {
    //build the sdk
    String sdk = "Boogle SDK";

    //then register the bean in spring context with constructor args
    context.registerBean(BoogleFeature.class,sdk);
  }

}

The bean to register dynamically:

public class BoogleFeature {

  private String sdk;

  public BoogleFeature(String sdk) {
    this.sdk = sdk;
  }

  public String doBoogle() {
    return "Boogling with " + sdk;
  }
}

You can then use, Anywhere in your app:

@Component
class AClassUsingBoogleFeature {
   @Autowired
   BoogleFeature boogleFeature; //<-- this will have the sdk instantiated already
}

The following test proves that, after spring context initialization,
(which will initialize BooglerFactory then call the @Postcontruct method BTW),
you can use Boogler with @Autowired anywhere.

@SpringBootTest
public class BooglerTest {

  @Autowired
  BoogleFeature boogleFeature;

  @Test
  void boogleFeature_ShouldBeInstantiated() {
    assert "Boogling with Boogle SDK".equals(boogleFeature.doBoogle());
  }

}

registerBean has more powerful options, check it out here.

Upvotes: 0

Shailesh Chandra
Shailesh Chandra

Reputation: 2340

did you try below, you can put below code in come configuration class

    @Bean(name="boggleFeature")
    public BoggleFeature createBoggleClient() {
        SDKPersona.SDKPersonaBuilder sdkBuilder =
            new AppIdentifier.SDKPersonaBuilder()
                .setRegistryId(config.getRegistryId())
                .setRegistrySecret(config.getRegistrySecret())
    
        return new BoggleFeature(sdkBuilder.build());
    }
       
    

Then you can use with autowired any where

 @Autowired
    private BoogleFeature boogle

Upvotes: 3

Related Questions