【问题标题】:Wire multiple config classes using dependency injection使用依赖注入连接多个配置类
【发布时间】:2016-05-10 11:51:17
【问题描述】:

我在春季有工作配置课程。我尝试使用依赖注入通过配置映射替换硬编码字符串。

@Configuration
@Component
public class BwlConfiguration {

    @Resource(name="loadParameters")
    private Map<ConfigEnum, String> conf;

    private String address;

    public BwlConfiguration() {
        address = conf.get(SPI_BL);
    }
...
}

提供conf map的类:

@Configuration
@Component
public class ConfigLoader {

    @Resource(name="returnEnv")
    private Map<String, String> env;

    @Bean
    public Map<ConfigEnum, String> loadParameters() throws ParameterNotSetException{
        ....
        return parameterMap;
    }

提供环境映射的类:

@Configuration
public class EnvConf {


    @Bean
    public Map<String, String> returnEnv(){
        return System.getenv();
    }   
}

当我运行程序时,nullPointerException 在address = conf.get(SPI_BL); 行被抛出。我试图用@Import(...class) 替换@Component,结果相同,它失去了注入点。 我使用这些注释错了吗?谢谢

【问题讨论】:

  • 你在哪里用@Import替换了@Component;在BwlConfiguration,还是在ConfigLoaderEnvConf?不要从任何类中删除@Component。将@Import({ConfigLoader.class, EnvConf.class}) 添加到BwlConfiguration
  • 谢谢建议,结果还是一样,还是空指针。
  • @Jesper 为什么在@Configuration 上需要@Component
  • @DeendayalGarg 我的错,您实际上不需要在@Configuration 类上添加@Component 注释。
  • 我发现了错误。错误是我在配置类的构造函数中使用并分配了通过注入检索到的值。

标签: java spring dependency-injection spring-boot config


【解决方案1】:

我将BwlConfiguration 中的构造函数替换为:

@Bean
public String address(){
    return conf.get(SPI_BL);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    相关资源
    最近更新 更多