Spring属性(property-placeholder)自动装配

Pio*_*zda 40 spring dependency-injection properties

我有我的applicationContext.xml

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


<bean id="clientPreferencesManager" class="pl.bildpresse.bildchat2.business.ClientPreferencesManager" >
    <property name="clientApiUrl" value="${clientapi.url}" />     
</bean>
Run Code Online (Sandbox Code Playgroud)

是否有可能通过autowire做同样的事情?就像是 :

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

axt*_*avt 78

你可以使用@Value:

@Value("${clientapi.url}") 
public void setClientApiUrl(String clientApiUrl) { 
    this.clientApiUrl = clientApiUrl; 
}
Run Code Online (Sandbox Code Playgroud)


Fel*_*lix 8

我花了一些时间来理解为什么它不起作用.我总是用一个#而不是一个$.我总是得到这样的信息:

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

只需改变它:

@Value("#{secretkey}')
Run Code Online (Sandbox Code Playgroud)

@Value('${secretkey}')
Run Code Online (Sandbox Code Playgroud)

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


Cos*_*sta 5

好.刚刚得到它.你需要添加@Autowired之类的东西:

@Autowired
@Value("${clientapi.url}") 
private StringValueResolver resolver;
Run Code Online (Sandbox Code Playgroud)

我正在使用spring 3.0.0.RELEASE

干杯