如何在 PostConstruct 时在 spring 中自动装配此依赖项

问题描述

我在 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...