【发布时间】: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,还是在ConfigLoader和EnvConf?不要从任何类中删除@Component。将@Import({ConfigLoader.class, EnvConf.class})添加到BwlConfiguration。 -
谢谢建议,结果还是一样,还是空指针。
-
@Jesper 为什么在
@Configuration上需要@Component? -
@DeendayalGarg 我的错,您实际上不需要在
@Configuration类上添加@Component注释。 -
我发现了错误。错误是我在配置类的构造函数中使用并分配了通过注入检索到的值。
标签: java spring dependency-injection spring-boot config