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。 为什么?
最佳答案
@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
关于java - @Value 和 @PropertySource ("classpath:application.properties")始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33016434/