我们可以使用<context:property-placeholder>
来外部化属性,并且可以通过如下配置<context:property-override>
来覆盖Spring bean的属性:
<context:property-placeholder location="classpath:application.properties"/>
<context:property-override location="classpath:override.properties"/>
我想将XML配置移动到JavaConfig。
@Configuration
@ComponentScan
@PropertySource("classpath:application.properties")
public class AppConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
但是,如何使用注释配置我的替代属性?
PS:
我有一个豆说MyBean如下:
@Component
public class MyBean {
@Value("${someProp}")
private String someProp;
}
在我的
application.properties
中,我有someProp=TestValue
在我的
override.properties
中,我将someProp值覆盖为myBean.someProp=RealValue
最佳答案
不,不是。
但是您可以在配置类中创建PropertyOverrideConfigurer
类型的Bean,但结果相同。
更新
例如:
@Bean public static PropertyOverrideConfigurer propertyOverrideConfigurer() {
PropertyOverrideConfigurer overrideConfigurer = new PropertyOverrideConfigurer();
overrideConfigurer.setLocation(new ClassPathResource("override.properties"));
return overrideConfigurer;
}
请注意静态修饰符,这是因为BFPP应该在容器生命周期的早期实例化。
有关更多信息,请参见http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Bean.html。