问题描述
我在 spring 托管代码的 @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());
}
}
}
现在我不想做 boggle = new BoggleFeature(sdkBuilder.build());
并将其设为 bean 并将其注入为 deopendency 。我怎样才能做到这一点。
解决方法
你有没有试过下面的代码,你可以把下面的代码放在来配置类中
@Bean(name="boggleFeature")
public BoggleFeature createBoggleClient() {
SDKPersona.SDKPersonaBuilder sdkBuilder =
new AppIdentifier.SDKPersonaBuilder()
.setRegistryId(config.getRegistryId())
.setRegistrySecret(config.getRegistrySecret())
return new BoggleFeature(sdkBuilder.build());
}
然后你可以在任何地方使用自动装配
@Autowired
private BoogleFeature boogle
,
您可以使用 GenericApplicationContext
以这种方式在 @PostConstruct
期间动态注册 bean:
@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
然后调用 @Postcontruct
方法顺便说一句),
您可以在任何地方将 Boogler
与 @Autowired
结合使用。
@SpringBootTest
public class BooglerTest {
@Autowired
BoogleFeature boogleFeature;
@Test
void boogleFeature_ShouldBeInstantiated() {
assert "Boogling with Boogle SDK".equals(boogleFeature.doBoogle());
}
}
registerBean
有更强大的选项,check it out here。