【问题标题】:Acquiring a spring configuration value from a custom class从自定义类获取弹簧配置值
【发布时间】:2010-10-19 02:06:08
【问题描述】:

我正在考虑使用 Spring 来组装我的应用程序的组件,但是我遇到了一个问题。我们的应用程序使用对 VM 来说是全局的配置存储库,并且类似于(但不完全是)系统属性。

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

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

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

鉴于我是 Spring 新手,代码示例将使我的生活变得更轻松。

【问题讨论】:

    标签: java spring configuration


    【解决方案1】:

    你可以完全在配置中做到这一点(我并不是说这真的很漂亮;):

    <bean id="database" class="com.acme.Configuration" factory-method="getDb" />
    
    <bean class="com.acme.YourHost">
      <property name="yourProperty">
        <bean factory-bean="database" factory-method="get">
          <constructor-arg value="some_property_name" />
        </bean>
      </property>
    </bean>
    

    很高兴 Spring 3.0 将包含针对此类情况的表达式语言(请参阅blog post):)。

    【讨论】:

      【解决方案2】:

      为了扩展 cletus 的建议,我想说您想要一个 PropertyPlaceholderConfigurer 的自定义子类,并覆盖 resolvePlaceholder() 方法,该方法将调用您的 Configuration.getDb() 代码。如果您无法解析该值,则委托回超类。

      例如:

      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 将自动咨询您的类来解析占位符值。

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

      阅读有关 PropertyPlaceholderConfigurer 基本用法的参考文档,了解它的工作原理。它非常灵活。

      【讨论】:

        【解决方案3】:

        您可以这样做,尽管这不是处理配置数据的建议方法。请参阅 Spring 参考文档的3.7 Container extension points

        基本上你会想要创建一个自定义的 BeanFactoryPostProcessor 实现来替换如下表达式:

        ${some_property_name}
        

        根据回调使用适当的值。

        以 PropertyPlaceholderConfigurer 的实现为起点。

        【讨论】:

          猜你喜欢
          • 2017-01-22
          • 2012-10-18
          • 2011-09-11
          • 2019-09-26
          • 2013-10-15
          • 1970-01-01
          • 2018-03-04
          • 1970-01-01
          相关资源
          最近更新 更多