【问题标题】:Using spring3 @Value to access PropertyPlaceholderConfigurer values?使用 spring3 @Value 访问 PropertyPlaceholderConfigurer 值?
【发布时间】:2009-11-16 12:41:12
【问题描述】:

当我的属性源是PropertyPlaceholderConfigurer 的子类时,我正在尝试使用@Value 在spring bean 中设置字符串的值。有人知道怎么做吗?

【问题讨论】:

    标签: spring spring-el


    【解决方案1】:

    老问题,但仍然值得回答。您可以像使用原始 PropertyPlaceholderConfigurer 一样使用表达式。

    app.properties

        app.value=Injected
    

    app-context.xml

        <bean id="propertyConfigurer" class="MyPropertyPlaceholderConfigurer">
          <property name="location">
            <value>file:app.properties</value>
          </property>
        </bean>
    

    在目标 bean 中

        @Value(value="${app.value}")
        private String injected;
    

    使用 Spring 3.0.6 测试了这种方法

    【讨论】:

    • 额外的 #{...} 有点没用(它对静态字符串进行 SpEL 评估)。从 Spring 3.x 开始,@Value 注释中支持 ${app.value} 语法,并且可以用于注入属性(但可能不是在提出这个问题时)。
    • 关于额外的#{...},您是正确的。您可以省略它,您将获得相同的结果。我会更正我的答案以摆脱它。
    【解决方案2】:

    您是否设法通过使用属性语法从 bean 定义文件中显式注入值来使其工作?理论上,如果可行,那么您应该能够在@Value 中使用相同的表达式。就此而言,您应该也可以使用@Autowired @Qualifier 来做到这一点

    【讨论】:

      【解决方案3】:

      我认为在@Value 注释中使用SPEL 访问PropertyPlaceHolderConfigurer 加载的属性是不可能的。这会很棒,但据我所知,下一个最好的事情是声明:

      <util:properties id="props" location="classpath:xxx/yyy/app.props"/>
      

      它可以指向与您的PropertyPlaceHolderConfigurer 相同的属性文件。

      【讨论】:

      • 您还可以创建自己的 PropertyPlaceHolderConfigurer 来公开其属性。您可以在这里找到一个示例:mortarproject.svn.sourceforge.net/viewvc/mortarproject/src/… 您必须使用旧的 而不是新的 来注册它,这样您就可以设置一个 id 然后引用它在您的值标签中作为 @Value(#{xxx.properties['foo.bar']})
      • 我认为你不需要输入 xxx.properties 文件名,spring 加载所有属性文件,你只需要确保你的密钥在所有属性文件中是唯一的。
      • 这是不正确的。从 spring 3 开始,您可以使用 SPEL 访问 PropertyPlaceHolderConfigurer 值。
      猜你喜欢
      • 2013-03-04
      • 2015-07-18
      • 2019-07-21
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多