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
@PropertySource("classpath:application.properties")
public class HibernateUtil {
static {
try {
Properties prop= new Properties();
if(local){
[..]
} else {
[..]
}
}
我需要在本地或远程配置我的数据库,我不能。 " Hibernate.class中的本地"始终返回null。 为什么?
答案 0 :(得分:1)
@PropertySource("classpath:application.properties")
是一个在加载Spring的应用程序上下文时加载属性文件的注释,因此它应该在配置类中使用,需要@Configuration
,如:
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
}
你需要一段额外的代码来声明一个静态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();
}
}
有助于解决@Value和$ {...}占位符,请参阅:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.html