40

I have in my applicationContext.xml

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


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

Is it possible to do the same by autowire ? Something like :

@Autowired
@Qualifier("${clientapi.url}")
public void setClientApiUrl(String clientApiUrl) {
    this.clientApiUrl = clientApiUrl;
}
Visruth
  • 3,430
  • 35
  • 48
Piotr Gwiazda
  • 12,080
  • 13
  • 60
  • 91

5 Answers5

79

You can use @Value:

@Value("${clientapi.url}") 
public void setClientApiUrl(String clientApiUrl) { 
    this.clientApiUrl = clientApiUrl; 
}
axtavt
  • 239,438
  • 41
  • 511
  • 482
8

It took me some time to understand why it didn't work. I always used a # instead of a $. I always got the message:

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

Just had to change it from:

@Value("#{secretkey}')

to

@Value('${secretkey}')

I hope this saves somebody's time.

Felix
  • 1,097
  • 1
  • 10
  • 16
5

Ok. Just got it. You need to add @Autowired Something like:

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

I'm using spring 3.0.0.RELEASE

Cheers

sjngm
  • 12,423
  • 14
  • 84
  • 114
Costa
  • 171
  • 1
  • 3
  • 5
2

For spring 3.0, the correct way is the one shown - using @Value("${expression}")

For spring pre-3.0, you can try:

@Autowired
private StringValueResolver resolver;

There were no context initialization problems here, but I'm not sure it will work. Using the resolver you can resolve properties.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1

My solution is to use

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

and then in clientapi.properties file

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

This one is good too

Piotr Gwiazda
  • 12,080
  • 13
  • 60
  • 91