具有YamlPropertiesFactoryBean和Spring Boot的属性占位符



我正在将一个小型"遗留"应用程序迁移到Spring Boot,遇到了属性占位符与YamlPropertiesFactoryBean组合的问题。该应用程序使用Spring XML配置。

我在项目中添加了一个Spring Boot"main",如下所示:

@SpringBootApplication
@ImportResource("classpath:spring-config.xml")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

我在/config中放入了一个application.yaml。它由Spring引导获取,我可以通过导入的Spring-config.xml中的bean声明中的属性替换(${some.prop}(来访问其中定义的属性。例如

<bean id="myRouteBuilder" class="org.camelSpringBoot.test.MyRouteBuilder">
<property name="someProp" value="${prop.from.application.yaml}"/>
</bean>

使用org.springframework.beans.factory.config.YamlPropertiesFactoryBean读取额外的外部配置文件时除外:无法解析org.springframework.core.io.FileSystemResource的构造函数arg中文件位置的属性:

<bean id="yamlProperties" class="org.springframework.beans.factory.config.YamlPropertiesFactoryBean">
<property name="resources">
<list>
<bean class="org.springframework.core.io.FileSystemResource">
<constructor-arg value="${service.config.loc}" />
</bean>
</list>
</property>
</bean>

产生

java.io.FileNotFoundException:${service.config.loc}

如果我硬编码外部配置的位置,那么外部YAML文件中使用的属性也不会被解析。

application.yaml:

security:
keystore:
loc:      /security/my.keystore

外部配置:

services:
a:
ssl:
secret: ${security.keystore.loc}

java.lang.RuntimeException:无法打开密钥库/信任库${security.keystore.loc}

请注意,该错误会抱怨逐字逐句的属性。

YamlPropertiesFactoryBean实例是在spring-config.xml中声明的,就像其他成功使用属性占位符的bean一样(意味着属性会被其值替换(。为什么YamlPropertiesFactoryBean会失败

是否可以为外部YAML文档启用占位符解析?

我不知道它是否能像你想做的那样工作。属性解析是在BeanDefinition完成后进行的,因此只能使用Spring Beans,而不能使用像yaml文件这样的任意文件。

大多数构建工具(gradle、maven(都包含在构建时解析这些占位符的功能。这对你来说可能是个解决方案吗?

最新更新