问题描述
我一直在打破这个问题。不知道我错过了什么。我无法获得 @Value
注释在纯java配置的spring应用程序(非web)中工作
I've been breaking my head on this one. Not sure what I am missing. I am unable to get the @Value
annotations to work in a pure java configured spring app(non 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如下:
The property file just contains my.prop=avalue
The bean is as follows:
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
姓名:$ {my.prop}
The environment variable prints the value properly, the @Value
does not.avalue
Name: ${my.prop}
主类只是初始化上下文。
The main class just initializes the context.
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class);
但是,如果我使用
@ImportResource("classpath:property-config.xml")
with此代码段
<context:property-placeholder location="app.properties" />
然后它运作正常。当然现在环境返回 null
。
then it works fine. Of course now the enviroment returns null
.
推荐答案
添加以下bean您的 Config
类中的声明
Add the following bean declaration in your Config
class
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
为了 @Value
注释工作 PropertySourcesPlaceholderConfigurer
应该注册。在XML中使用< context:property-placeholder>
时会自动完成,但应注册为 static @Bean
使用 @Configuration
时。
In order for @Value
annotations to work PropertySourcesPlaceholderConfigurer
should be registered. It is done automatically when using <context:property-placeholder>
in XML, but should be registered as a static @Bean
when using @Configuration
.
参见文档和本Spring Framework 。
See @PropertySource documentation and this Spring Framework Jira issue.
这篇关于使用纯Java配置的Spring 3.2 @value注释不起作用,但Environment.getProperty可以工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!