我有一个Spring3.1应用程序。假设它有一个包含以下内容的XML:
<context:property-placeholder location="classpath:somename.properties" />
<context:property-placeholder location="classpath:xxx.properties" />我希望始终加载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>此外,这两个文件都具有相同键但值不同的属性。
但是它不能像后来的bean那样工作,因为它有一个属性的占位符,该属性的键是在xx1.properties (和xx2.properties)中定义的,这使得Spring抱怨在应用程序上下文中找不到键。
发布于 2015-03-02 01:33:23
我已经决定提交并回答这个问题,因为它还没有被接受。它可能不是你特别想要的,但它对我很有效。还要注意,我使用的是新的注释驱动配置,但是它可以移植到xml配置中。
我为每个环境(dev.properties、test.properties等)都有一个属性文件
然后我有了一个RootConfig类,它是用于所有配置的类。这个类中只有两个注释:@Configuration和@ComponentScan(basePackageClasses=RootConfig.class).这告诉它扫描与它相同的包中的任何内容。
然后有一个配置,其中包含了我所有的正常配置。在与上面的根配置类相同的包中,每个环境也有一个配置。
特定于环境的配置只是具有以下注释的标记类,用于将其指向特定于环境的属性文件:
@Configuration
@PropertySource("classpath:dev.properties")
@Import(NormalConfig.class)
@Profile("dev")导入告诉它引入普通的config类。但当它进入其中时,它将设置特定于环境的属性。
发布于 2012-12-25 19:12:01
您可以执行以下操作:
<context:property-placeholder location="classpath:${spring.profiles.active}.properties" />它工作得很好,但可能不适合同时使用多个配置文件。
在声明2个属性占位符时,如果第一个占位符不包含所有应用程序键,则应将属性放入忽略unresolvable = true的属性中,以便可以使用第二个占位符。我不确定这是否是你想要做的,如果你想同时激活xx1和xx2配置文件,可能会这样做。
注意,像这样声明2个属性占位符使它们独立,并且在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>您创建的文件:
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);
}
}一旦你这样做了,你只需要在你的上下文中添加:
<context:property-placeholder/>这是处理spring属性的最好方法,因为您不再到处声明本地属性,您可以编程控制正在发生的事情,并且属性源xx1值可以在xx2.properties中使用。
在工作中,我们正在使用它,它工作得很好。我们注册了3个额外的属性源:-基础设施:由Puppet - profile提供:根据配置文件加载的不同属性。- Common:包含默认值,当所有配置文件共享相同的值时,等等...
https://stackoverflow.com/questions/10669474
复制相似问题