gpt4 book ai didi

spring - 如何通过 XML 配置中的名称访问 @ConfigurationProperties bean?

转载 作者:行者123 更新时间:2023-12-04 00:03:38 25 4
gpt4 key购买 nike

假设我有一个 AppProperties带有 @ConfigurationProperties("app") 注释的 POJO .它包含不同的应用程序属性,我通常使用这些属性在 @Configuration 中配置我的 bean。类。@EnableConfigurationProperties(AppProperties.class)使其可用于 @Autowiring ,这对于Java配置非常方便。

但是我的应用程序上下文的一部分是使用老式的 XML 配置配置的。我想知道如何访问@ConfigurationProperties AppProperties XML配置中的bean?如果只有 @EnableConfigurationProperties让我有能力提供 name ,我可以像这样在 XML 中使用 SpEL:#{appProperties.requiredProp} (我真的很想实现它)。

不幸的是,我没有看到提供名称的方法,并且我尝试使用建议的 appProperties名称失败:

SpelEvaluationException: EL1008E: Property or field 'appProperties' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext' - maybe not public or not valid?



我在调试器中看到该 bean 实际上被称为 app-my.package.AppProperties这并不明显,也从未明确说明过。

在 JavaDoc 中为 @EnableConfigurationProperties我注意到以下内容:

@ConfigurationProperties beans can be registered in the standard way (for example using @Bean methods) or, for convenience, can be specified directly on this (@EnableConfigurationProperties) annotation.



这是否意味着我可以通过某种方式获得 AppProperties 的命名实例?从 application.properties 注入(inject)的值使用 @Bean Java 中的方法或 <bean/>在 XML 中?

当然,我可以 Autowiring 整个 AppProperties到用XML配置的类,但我不认为这是一个好的设计解决方案,因为我只对单个 String感兴趣来自 AppProperties 的属性(property).可能我不应该尝试在 XML 中使用这种“类型安全”的属性方式,而只是坚持旧方式:使用 ${} -分辨率,但我觉得我在 @ConfigurationProperties 中遗漏了一些东西概念所以请告诉我。

最佳答案

有两种注册配置属性 bean 的方法。

注册 @EnableConfigurationProperties .

 @EnableConfigurationProperties(AppProperties.class)
public class Application {}

@ConfigurationProperties("app")
public class AppProperties {}
@EnableConfigurationProperties注解会自动注册 AppProperties作为 bean 的类,称为 prefix-your.package.AppProperties ,当您按如下方式包含类时: @EnableConfigurationProperties(AppProperties.class)AppProperties有一个前缀, @ConfigurationProperties("app") .

注册 @Component@Bean
 @EnableConfigurationProperties
public class Application {}

@Component
@ConfigurationProperties("app")
public class AppProperties {}

或者
@EnableConfigurationProperties
public class Application {

@Bean
@ConfigurationProperties("app")
public AppProperties appProperties() {
return new AppProperties();
}

}
@Component@Bean将注册一个名为 appProperties 的 bean .
通过使用第二种方法,您将能够使用 SpEL 获取属性 #{appProperties.requiredProp}

关于spring - 如何通过 XML 配置中的名称访问 @ConfigurationProperties bean?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53999391/

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