gpt4 book ai didi

java - Spring @ConfigurationProperties 解析器忽略外部化属性

转载 作者:行者123 更新时间:2023-12-02 09:04:16 46 4
gpt4 key购买 nike

我使用 @ImportResource({"classpath:property-sources.xml"}) 注释来外部化某些配置文件的路径。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">

<util:properties id="externalProperties"
ignore-resource-not-found="true"
location="file:${dir.data}/foo.properties"
/>

<context:property-placeholder ignore-unresolvable="true" properties-ref="externalProperties"/>
</beans>

因此,在应用程序中,我可以使用 @Valuefoo.properties 注入(inject)任何属性。是的,很常见。

但是,当我尝试使用 @ConfigurationProperties 来执行相同的操作时,Spring Boot 完全忽略该文件中的任何属性。起初我以为配置有问题,但如果我将完全相同的属性放入 application.yml 中,它就可以工作。比较:

foo.properties(被@ConfigurationProperties解析器忽略)

descriptions.foo.bar.baz = test

application.yml(由@ConfigurationProperties解析器成功处理)

descriptions:
foo:
bar:
baz: test

应该没有区别。另外,bean 本身没有什么特别的:

@ConfigurationProperties(prefix = "descriptions", ignoreUnknownFields = false)
public class Descriptions {

private Map<String, String> foo = new HashMap<>();

public Map<String, String> getFoo() {
return foo;
}

public void setFoo(Map<String, String> foo) {
this.foo = foo;
}
}

为什么@Value始终有效,而@ConfigurationProperties仅适用于application.yml

最佳答案

在 XML 文件中,您将属性文件加载到 Properties 对象中,然后将其传递给另外配置的 PropertySourcePlaceholderConfigurer。这就是命名空间魔法的作用。

PropertySourcePlaceholderConfigurer 将使用属性来解析 @Value 或 xml 中的值表达式。它不会将加载的属性添加到环境中。 Environment 是 Spring Boot 中的 ConfigurationPropertiesBindingPostProcessor 使用的环境。这也在流程的早期运行。

相反,您应该做的是将 @PropertySource 放在您的 @SpringBootApplication 注释类上:

@PropertySource(value="file:${dir.data}/foo.properties", ignoreResourceNotFound=true)

或者使用 spring.config.additional-location 属性指定要加载的附加配置文件。

--spring.config.additional-location=file:${dir.data}/foo.properties

对于后者,您不需要更改任何内容,只需指定在启动时加载哪些文件即可。

关于java - Spring @ConfigurationProperties 解析器忽略外部化属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59947540/

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