Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring properties (property-placeholder) autowiring

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; } 
like image 206
Piotr Gwiazda Avatar asked May 21 '10 13:05

Piotr Gwiazda


People also ask

What is placeholder Spring?

The context:property-placeholder tag is used to externalize properties in a separate file. It automatically configures PropertyPlaceholderConfigurer , which replaces the ${} placeholders, which are resolved against a specified properties file (as a Spring resource location).

How do I set environment specific properties in Spring boot?

Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.

How do I load a properties file in Spring?

Parse properties file with @ConfigurationProperties in a Spring boot. @ConfigurationProperties in spring boot is another way to read properties files. Add setters and getters for a member variable. Object of this class holds the content of properties with values.


2 Answers

You can use @Value:

@Value("${clientapi.url}")  public void setClientApiUrl(String clientApiUrl) {      this.clientApiUrl = clientApiUrl;  } 
like image 110
axtavt Avatar answered Sep 18 '22 09:09

axtavt


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.

like image 24
Felix Avatar answered Sep 17 '22 09:09

Felix