在这件事上我已经伤透了脑筋。不确定我错过了什么。我无法让@Value
注释在纯java配置的spring应用程序(非web)中工作
@Configuration
@PropertySource("classpath:app.properties")
public class Config {
@Value("${my.prop}")
String name;
@Autowired
Environment env;
@Bean(name = "myBean", initMethod = "print")
public MyBean getMyBean(){
MyBean myBean = new MyBean();
myBean.setName(name);
System.out.println(env.getProperty("my.prop"));
return myBean;
}
}
属性文件只包含my.prop=avalue
。bean如下所示:
public class MyBean {
String name;
public void print() {
System.out.println("Name: " + name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
环境变量正确地打印值,而@Value
不能。
avalue
Name: ${my.prop}
主类只是初始化上下文。
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
但是,如果我使用
@ImportResource("classpath:property-config.xml")
使用下面的代码片段
<context:property-placeholder location="app.properties" />
那么它工作得很好。当然,现在环境返回null
。
发布于 2013-06-14 06:44:19
在Config
类中添加以下bean声明
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
为了让@Value
注解起作用,应该注册PropertySourcesPlaceholderConfigurer
。当在XML中使用<context:property-placeholder>
时,它是自动完成的,但是当使用@Configuration
时,应该注册为static @Bean
。
请参阅@PropertySource文档和这个Spring框架Jira issue。
https://stackoverflow.com/questions/17097521
复制相似问题