2

@PostConstruct在弹簧托管代码的块内有以下代码。


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());
        }
    }
}

现在我不想做 aboggle = new BoggleFeature(sdkBuilder.build());并将其作为 bean 并将其作为 deopendency 注入。我怎样才能做到这一点。

4

2 回答 2

3

你在下面尝试了吗,你可以把下面的代码放在来配置类中

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

然后你可以在任何地方使用 autowired

 @Autowired
    private BoogleFeature boogle
于 2021-03-05T10:16:36.147 回答
0

您可以使用这种方式GenericApplicationContext动态注册 bean @PostConstruct

@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);
  }

}

动态注册的bean:

public class BoogleFeature {

  private String sdk;

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

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

然后,您可以在应用程序中的任何位置使用:

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

下面的测试证明,在 spring 上下文初始化之后
(它将初始化BooglerFactory然后调用@PostcontructBTW 方法),
您可以在任何地方使用Booglerwith @Autowired

@SpringBootTest
public class BooglerTest {

  @Autowired
  BoogleFeature boogleFeature;

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

}

registerBean有更强大的选项,请在此处查看

于 2021-03-05T20:42:25.670 回答