Java @带有@PropertySource(“classpath:application.properties”)的值始终返回null
应用程序属性Java @带有@PropertySource(“classpath:application.properties”)的值始终返回null,java,spring,config,Java,Spring,Config,应用程序属性 local=true @PropertySource("classpath:application.properties") public class HibernateUtil { static { try { Properties prop= new Properties(); if(local){ [..] } else {
local=true
@PropertySource("classpath:application.properties")
public class HibernateUtil {
static {
try {
Properties prop= new Properties();
if(local){
[..]
} else {
[..]
}
}
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
local=true
@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和${…}占位符,请参见:@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和${…}占位符,请参阅:对不起,我忘记添加此数据,但我的配置中有它如果它是Spring boot应用程序,您可以删除@PropertySource和静态PropertySourcesplaceConfigurer,Spring boot将自动搜索资源文件夹中的application.properties抱歉,我忘了添加此数据,但我的配置中有它如果它是Spring boot应用程序,您可以删除@PropertySource和静态PropertySourcesplaceConfigurer,Spring boot将自动搜索资源文件夹中的application.properties这不适合meThis这不适合我