在上下文启动之前提供外部Bean

时间:2017-06-08 12:27:15

标签: java spring

我正在为服务开发Java API,我想将其解压缩到库中。 我正在使用 spring 4.3.3

现在有一个名为ApiConfig的bean,它很简单。

public class ApiConfig {
   private String host;
   private String username;
   private String password;
}

并从属性文件中读取值。

我希望能够构建并提供此类上下文开始之前(几个组件将此类作为@Autowired依赖项)。

例如:

public class LoginService {

    @Autowired
    private ApiConfig apiConfig

    [...]
}

基本上,我想做这样的事情:

public static MyApi get(ApiConfig apiConfig) {

     //Here I want to provide this apiConfig as singleton bean that would be used everywhere
    provide somehow this class as bean
    // here all beans are loaded and the it fails because it cannot resolve ApiConfig
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ContextConfig.class);
    MyApi myApi= context.getBean(MyApi.class);
    return myApi;
}

通过在pom.xml中添加依赖项,其他Java应用程序将使用方法MyApi.get(AppConfig)

有没有办法可以做到这一点?提供ApiConfig bean然后初始化所有应用程序?

基本上让Spring知道在使用new AnnotationConfigApplicationContext(ContextConfig.class)

开始上下文之前还有这个bean

更新

在使用此库的任何应用程序中,这个想法都是这样的。

public static void main(String asdas[]) {
    ApiConfig config = new ApiConfig();
    config.setUsername("BOBTHEUSER");
    //config.set etc
    MyApi api = MyApi.get(config);
    api.doOperation();

1 个答案:

答案 0 :(得分:0)

实际上@Autowire就足够了。使ApiConfig成为Bean并在需要的地方自动装配它。 Spring解决了正确的顺序。

如果您有两个bean,并且需要在创建之前初始化第二个bean,请使用@DependsOn注释

@Configuration
public class MainConfig  {
    @Autowired
    private ApiConfig apiConfig

    @Bean(name="apiConfig")
    public ApiConfig apiConfig(){
        ... init the config ...
        return apiConfigInstance;
    }

    @Bean(name="myApi")
    @DependsOn("apiConfig")
    public MyApi myApi(){
        MyApi api = new MyApi(apiConfig);
        return api;
    }
} 

来自the example修改后的代码

相关问题