我想为不同的配置文件(生产和开发)配置属性。
这是我的配置:
@Configuration
public class PropertyPlaceholderConfig {
@Profile(Profiles.PRODUCTION)
static class ProductionConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigure()
throws IOException {
PropertySourcesPlaceholderConfigurer propertySources =
new PropertySourcesPlaceholderConfigurer();
propertySources.setIgnoreUnresolvablePlaceholders(Boolean.TRUE);
Resource[] resources =
ObjectArrays.concat(getCommonResources(), getProductionResources(), Resource.class);
propertySources.setLocations(resources);
return propertySources;
}
private static Resource[] getProductionResources() throws IOException {
return new PathMatchingResourcePatternResolver()
.getResources("classpath:properties/production/*.properties");
}
}
@Profile(Profiles.DEV)
static class DevConfiguration {
@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigure()
throws IOException {
PropertySourcesPlaceholderConfigurer propertySources =
new PropertySourcesPlaceholderConfigurer();
propertySources.setIgnoreUnresolvablePlaceholders(Boolean.TRUE);
Resource[] resources =
ObjectArrays.concat(getCommonResources(), getDevResources(), Resource.class);
propertySources.setLocations(resources);
return propertySources;
}
private static Resource[] getDevResources() throws IOException {
return new PathMatchingResourcePatternResolver()
.getResources("classpath:properties/dev/*.properties");
}
}
private static Resource[] getCommonResources() throws IOException {
return new PathMatchingResourcePatternResolver()
.getResources("classpath:properties/common/*.properties");
}
}
我打印了当前配置文件(dev)和加载的文件(所有文件都已正确加载到Resouce数组中)。我想在数据库配置中使用这个加载的属性。怎么做? 我用过:
@Import(PropertyPlaceholderConfig.class)
在课堂上,
和
@Autowired
private Environment environment;
但
environment.getProperty("h2.driverClass");
或
environment.resolvePlaceholders("${h2.driverClass}");
不起作用。
如何使用PropertySourcesPlaceholderConfigurer加载的属性?
我知道我可以在字段中使用@Value但是可以避免创建15个字段吗?