我正在考虑使用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配置值
发布评论