Eug*_*ras 2 java spring config
应用程序属性
local=true
Run Code Online (Sandbox Code Playgroud)
应用程序配置.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();
}
Run Code Online (Sandbox Code Playgroud)
HibernateUtil.类
@PropertySource("classpath:application.properties")
public class HibernateUtil {
static {
try {
Properties prop= new Properties();
if(local){
[..]
} else {
[..]
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在本地或远程配置我的数据库,但我不能。 “Hibernate.class 中的本地”始终返回 null。为什么?
@PropertySource("classpath:application.properties")是一个注释,用于在加载Spring应用程序上下文时加载属性文件,因此应该在配置类中使用它,您需要@Configuration像:
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
}
Run Code Online (Sandbox Code Playgroud)
并且您需要一段额外的代码来声明静态 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();
}
}
Run Code Online (Sandbox Code Playgroud)
它有助于解析 @Value 和 ${...} 占位符,请参阅:http ://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/support/PropertySourcesPlaceholderConfigurer.html
| 归档时间: |
|
| 查看次数: |
23467 次 |
| 最近记录: |