java @Value 和 @PropertySource("classpath:application.properties") 总是返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33016434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
@Value with @PropertySource("classpath:application.properties") allways return null
提问by Eugenio Valeiras
application.properties
应用程序属性
local=true
AppConfig.java
应用程序配置文件
@PropertySource("classpath:application.properties")
@Configuration
public class AppConfig {
@Value("${local}")
private Boolean local;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
if(local){
[..]
} else {
[..]
}
return dataSource;
}
}
@Bean
public PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
HibernateUtil.class
HibernateUtil.class
@PropertySource("classpath:application.properties")
public class HibernateUtil {
static {
try {
Properties prop= new Properties();
if(local){
[..]
} else {
[..]
}
}
I need to config my DB locally or remotely and I cant. "local in Hibernate.class" Always return null. Why?
我需要在本地或远程配置我的数据库,但我不能。 “Hibernate.class 中的本地”始终返回 null。为什么?
回答by Emilien Brigand
@PropertySource("classpath:application.properties")
is an annotation to load your properties file when the application context of Spring is loaded, so it should be used in a configuration class, you need @Configuration
like:
@PropertySource("classpath:application.properties")
是在加载 Spring 的应用程序上下文时加载属性文件的注释,因此它应该在配置类中使用,您需要@Configuration
像:
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
}
and you need an extra piece of code, to declare a static bean PropertySourcesPlaceholderConfigurer:
并且您需要一段额外的代码来声明一个静态 bean PropertySourcesPlaceholderConfigurer:
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
@Value("${local}")
private Boolean local;
//Used in addition of @PropertySource
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
it helps to resolve @Value and the ${...} placeholder, see: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.html
它有助于解决 @Value 和 ${...} 占位符,请参阅:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.html