我正在创建一个新项目并尝试使用Java配置,我之前使用的是XML配置。我的应用需要<property-placeholder>
之类的配置。我有一个如下配置:
@Configuration
@PropertySources({
@PropertySource(ignoreResourceNotFound = true,
value = "classpath:app.config.properties"),
@PropertySource(ignoreResourceNotFound = true,
value = "classpath:app.user.config.properties"),
@PropertySource(ignoreResourceNotFound = true,
value = "file:///${app.config}")
})
public class TestConfig {
@Autowired
Environment env;
@Value("${prop1}")
String prop1;
@Bean
public BasicData bd1() {
System.out.println(env.getProperty("prop1"));
System.out.println(prop1);
return new BasicData("Test");
}
env.getProperty(String)
按预期工作,但我虽然@Value
注释也可能有效。
配置通过MVC初始化程序实例化,如下所示:
public class AppInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{
RootConfig.class,
TestConfig.class,
SecurityConfig.class
};
}
以前我会使用以下方法使用XML配置实现此目的:
<context:property-placeholder
location="classpath:app.config.properties,classpath:app.user.config.properties,file:///${app.config}"
ignore-resource-not-found="true"/>
答案 0 :(得分:1)
@PropertySource
的文档说明属性来源已添加到Environment
。
* Annotation providing a convenient and declarative mechanism for adding a * {@link org.springframework.core.env.PropertySource PropertySource} to Spring's * {@link org.springframework.core.env.Environment Environment}. To be used in * conjunction with @{@link Configuration} classes.
占位符的替换由BeanFactoryPostProcessor
完成。这曾经是PropertyPlaceholderConfigurer
,但自从Spring 3.1开始PropertySourcesPlaceholderConfigurer
。我认为这是将这种类型的bean添加到上下文中的问题。其文档表明它针对Environment
:
* Specialization of {@link org.springframework.beans.factory.config.PlaceholderConfigurerSupport * PlaceholderConfigurerSupport} that resolves ${...} placeholders within bean definition * property values and {@code @Value} annotations against the current Spring {@link * Environment} and its set of {@link PropertySources}.
答案 1 :(得分:0)
管理解决方案。我将PropertySoure
(s
)移到RootConfig
,展示了PropertySourcesPlaceholderConfigurer
bean。
@PropertySources({
@PropertySource(ignoreResourceNotFound = true,
value = "classpath:app.config.properties"),
@PropertySource(ignoreResourceNotFound = true,
value = "classpath:app.user.config.properties"),
@PropertySource(ignoreResourceNotFound = true,
value = "file:///${app.config}")
})
public class RootConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}