从自定义类获取spring配置值

编程入门 行业动态 更新时间:2024-10-12 03:20:47
本文介绍了从自定义类获取spring配置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在考虑使用Spring来组装我的应用程序的组件,但我有一个问题。我们的应用程序使用VM的全局配置存储库,并且与系统属性相似(但不完全相同)。

I'm considering using Spring to assemble the components of my application, but I've got a problem. Our application uses a configuration repository that is global to the VM, and is similar (but not precisely) to the system properties.

此配置API的访问方式如下: / p>

This configuration API is accessed like so:

Configuration.getDb ().get ("some_property_name")

有没有办法在Spring xml bean文件中使用这个全局配置中的值? getDb 可能会根据配置库的当前状态(它有上下文)返回不同的值,但是我愿意声明Spring配置将完全在应用程序上下文初始化时加载。

Is there any way to use values from this global configuration in Spring xml bean files? getDb may return a different value depending on the current state of the configuration library (it has context), but I'm willing to make the statement that the Spring configuration will be fully-loaded at application context initialization time. Still, something more flexible would be fantastic.

由于我是Spring的新手,代码示例会让我的生活变得更加容易。

Given that I'm a Spring newbie, code examples would make my life a great deal easier.

推荐答案

要扩展cletus的suggesrion,我想说你想要一个自定义子类PropertyPlaceholderConfigurer,并重写resolvePlaceholder()方法, Configuration.getDb()代码。如果无法解析值,请委托回超类。

To expand on cletus' suggesrion, I'd say you want a custom subclass of PropertyPlaceholderConfigurer, and override the resolvePlaceholder() method, which would call your Configuration.getDb() code. If you can't resolve the value, then delegate back to the superclass.

例如:

public class MyPlaceholderConfigurer extends PropertyPlaceholderConfigurer { @Override protected String resolvePlaceholder(String placeholder, Properties props) { String value = Configuration.getDb().get(placeholder) if (value == null) { value = super.resolvePlaceholder(placeholder, props); } return value; } }

然后在应用程序中定义一个类型为MyPlaceholderConfigurer的bean上下文和spring会自动咨询您的类以解析占位符值。

Then just define a bean of type MyPlaceholderConfigurer in your application context, and spring will automagically consult your class to resolve the placeholder values.

如果您的Configuration.getDb()组件无法解析该值,超类允许spring查找值作为系统属性。或者,您可以将属性文件注入到bean中,也可以检查它。

If your Configuration.getDb() component can't resolve the value, then delegating back to the superclass allows spring to look up the value as a system property instead. Alternatively, you can inject a properties file into the bean, and it can check that also.

阅读参考文档的PropertyPlaceholderConfigurer的基本用法,怎么运行的。它非常灵活。

Read the ref docs on the basic usage of PropertyPlaceholderConfigurer, to get a feel for how it works. It's quite flexible.

更多推荐

从自定义类获取spring配置值

本文发布于:2023-11-27 20:04:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639413.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!