2010-05-21 68 views
38

我有我的applicationContext.xml春属性(属性占位符)自动装配

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


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

是否有可能通过自动装配这样做?喜欢的东西:

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

回答

76

您可以使用@Value

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

true,对于当前版本的spring 3.0。 (+1) – Bozho 2010-05-21 16:48:45

+1

所以这是美元符号!不是散列。谢谢你的提示。 @Value的javadocs误导了我 – 2012-03-30 20:30:00

+0

愚蠢的问题,但它从哪里得到$ {clientapi.url}? – user2441441 2016-06-14 22:24:07

2

对于春季3.0,正确的做法是所示的一个 - 用@Value("${expression}")

预3.0春天,你可以试试:

@Autowired 
private StringValueResolver resolver; 

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

1

我的解决方案是使用

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

,然后在clientapi.properties文件

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

这一个也好啊

5

确定。刚刚得到它。您需要添加@Autowired 喜欢的东西:

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

我使用的是春天3.0.0.RELEASE

干杯

8

我花了一些时间来了解它为什么没有工作。我总是使用#而不是$。我总是得到的消息:

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

刚把它从改变:

@Value("#{secretkey}') 

@Value('${secretkey}') 

我希望这样可以节省别人的时间。

+0

我被blokced这...这是修复!谢谢Felix – hashcoder 2014-11-02 06:34:37