【问题标题】:Spring properties (property-placeholder) autowiringSpring 属性(property-placeholder)自动装配
【发布时间】:2011-02-22 09:03:07
【问题描述】:

我的 applicationContext.xml 中有

<context:property-placeholder location="classpath*:*.properties" />


<bean id="clientPreferencesManager" class="pl.bildpresse.bildchat2.business.ClientPreferencesManager" >
    <property name="clientApiUrl" value="${clientapi.url}" />     
</bean>

是否可以通过 autowire 做同样的事情?类似的东西:

@Autowired
@Qualifier("${clientapi.url}")
public void setClientApiUrl(String clientApiUrl) {
    this.clientApiUrl = clientApiUrl;
}

【问题讨论】:

    标签: spring properties dependency-injection


    【解决方案1】:

    你可以使用@Value:

    @Value("${clientapi.url}") 
    public void setClientApiUrl(String clientApiUrl) { 
        this.clientApiUrl = clientApiUrl; 
    }
    

    【讨论】:

    • true,适用于 spring 3.0,即当前版本。 (+1)
    • 所以它是美元符号!不是哈希。谢谢你的提示。 @Value 的 javadocs 误导了我
    • 愚蠢的问题,但 ${clientapi.url} 从哪里得到??
    • @user2441441 来自类路径上的属性文件,很可能是application.properties
    【解决方案2】:

    我花了一些时间才明白为什么它不起作用。我总是使用# 而不是$。我总是收到消息:

    EL1008E:(pos 0): Field or property 'secretkey' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
    

    只需将其更改为:

    @Value("#{secretkey}')
    

    @Value('${secretkey}')
    

    我希望这可以节省一些人的时间。

    【讨论】:

    • 我被这个阻止了......这是修复!谢谢菲利克斯
    【解决方案3】:

    好的。刚刚得到它。您需要添加@Autowired 比如:

    @Autowired
    @Value("${clientapi.url}") 
    private StringValueResolver resolver;
    

    我正在使用 spring 3.0.0.RELEASE

    干杯

    【讨论】:

      【解决方案4】:

      对于 spring 3.0,正确的方法是显示的方法 - 使用 @Value("${expression}")

      对于spring pre-3.0,可以试试:

      @Autowired
      private StringValueResolver resolver;
      

      这里没有上下文初始化问题,但我不确定它是否会起作用。使用解析器可以解析属性。

      【讨论】:

        【解决方案5】:

        我的解决方案是使用

        <context:property-override location="classpath:clientapi.properties" />
        

        然后在 clientapi.properties 文件中

        clientPreferencesManager.clientApiUrl=http://localhost:8084/ClientAPI/resources/
        

        这个也不错

        【讨论】:

          猜你喜欢
          • 2014-02-12
          • 2017-08-03
          • 1970-01-01
          • 1970-01-01
          • 2014-11-05
          • 1970-01-01
          • 1970-01-01
          • 2017-05-03
          • 2020-08-27
          相关资源
          最近更新 更多