gpt4 book ai didi

具有动态位置路径的 Spring PropertyPlaceholderConfigurer

转载 作者:行者123 更新时间:2023-12-02 10:05:58 24 4
gpt4 key购买 nike

我有以下基于 Spring XML 的配置:

<!--
These properties define the db.type property.
-->
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="order" value="1"/>
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="ignoreResourceNotFound" value="true" />
<property name="locations">
<list>
<!-- contains default db.type -->
<value>classpath:/default-cfg.properties</value>
<!-- db.type can be overridden by optional properties in the app work dir -->
<value>file:${app.work.dir}/cfg.properties</value>
</list>
</property>
</bean>

<!-- db.type should be used to get DB specific config properties -->
<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="order" value="2"/>
<property name="ignoreUnresolvablePlaceholders" value="false" />
<property name="ignoreResourceNotFound" value="false" />
<property name="locations">
<list>
<!-- does not work, ${db.type} does not get resolved -->
<value>classpath:/default-cfg-${db.type}.properties</value>
</list>
</property>
</bean>

问题是 classpath:/default-cfg-${db.type}.properties 位置中的属性未得到解析,即使 db.type由第一个属性占位符配置器定义。

我不断在日志中收到以下错误:

 class path resource [default-cfg-${db.type}.properties] cannot be opened because it does not exist

有什么方法可以使用PropertyPlaceholderConfigurer的locations属性中的属性吗?我想避免使用 JVM 系统属性来设置 db.type 值。

谢谢你,一月

最佳答案

由于 Alireza Fattahi 要求我提供代码,并且 WornOutSoles 建议接受的解决方案不起作用,因此我将发布基于 Spring ApplicationContextInitializer 的最终解决方案:

public class SpringProfilesActivator
implements ApplicationContextInitializer<XmlWebApplicationContext>
{
private static final Logger log = LoggerFactory.getLogger( SpringProfilesActivator.class );

...

@Override
public void initialize( XmlWebApplicationContext applicationContext )
{
// TODO: get your profiles from somewhere (config files, JVM system properties, database etc.)
String[] activeProfiles = new String[] { ... };

log.info( "Activating Spring profiles: {}", Arrays.toString( activeProfiles ) );

ConfigurableEnvironment env = applicationContext.getEnvironment();
env.setActiveProfiles( activeProfiles );
}

...
}

关于具有动态位置路径的 Spring PropertyPlaceholderConfigurer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16545990/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com