我有一个Spring 3.1应用程序。假设它具有包含以下内容的XML:
<context:property-placeholder location="classpath:somename.properties" />
<context:property-placeholder location="classpath:xxx.properties" />
Run Code Online (Sandbox Code Playgroud)
我希望始终加载some.properties(假设它存在),但是第二个占位符的xxx部分将根据活动的配置文件用某些名称替换。我已经试过了:
<beans profile="xx1">
<context:property-placeholder location="classpath:xx1.properties" />
</beans>
<beans profile="xx2">
<context:property-placeholder location="classpath:xx2.properties" />
</beans>
Run Code Online (Sandbox Code Playgroud)
此外,两个文件的属性均具有相同的键,但值不同。
但是它没有用,因为某些后来的Bean具有一个属性的占位符,该属性的键在xx1.properties(和xx2.properties)中定义,因此Spring抱怨说在应用程序上下文中找不到该键。
你可以做:
<context:property-placeholder location="classpath:${spring.profiles.active}.properties" />
Run Code Online (Sandbox Code Playgroud)
它可以正常工作,但同时使用多个配置文件时可能无法适应。
声明2个属性占位符时,如果第一个占位符不包含所有应用程序密钥,则应将属性设置为忽略unresolvable = true,以便可以使用第二个占位符。我不确定这是您要执行的操作,也可能希望同时激活xx1和xx2配置文件。
请注意,声明2个这样的propertyplaceholders使它们独立,并且在xx2.properties的声明中,您不能重用xx1.properties的值。
如果需要更高级的功能,可以在应用程序启动时注册PropertySources。
web.xml
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.xxx.core.spring.properties.PropertySourcesApplicationContextInitializer</param-value>
</context-param>
Run Code Online (Sandbox Code Playgroud)
您创建的文件:
public class PropertySourcesApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private static final Logger LOGGER = LoggerFactory.getLogger(PropertySourcesApplicationContextInitializer.class);
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
LOGGER.info("Adding some additional property sources");
String profile = System.getProperty("spring.profiles.active");
// ... Add property sources according to selected spring profile
// (note there already are some property sources registered, system properties etc)
applicationContext.getEnvironment().getPropertySources().addLast(myPropertySource);
}
}
Run Code Online (Sandbox Code Playgroud)
完成后,只需在上下文中添加:
<context:property-placeholder/>
Run Code Online (Sandbox Code Playgroud)
恕我直言,这是处理spring属性的最佳方法,因为您不再在任何地方声明局部属性,可以通过编程方式控制所发生的事情,并且可以在xx2.properties中使用属性源xx1值。
在工作中,我们正在使用它,并且效果很好。我们注册了3个其他属性源:-基础结构:由Puppet提供-配置文件:根据配置文件加载的其他属性。-通用:当所有配置文件共享相同的值时包含默认值,等等。
| 归档时间: |
|
| 查看次数: |
9440 次 |
| 最近记录: |