Main Tutorials

Spring – ${} is not working in @Value

A simple Spring @PropertySource example to read a properties file.

db.properties

db.driver=oracle.jdbc.driver.OracleDriver
AppConfig.java

@Configuration
@PropertySource("classpath:db.properties")
public class AppConfig {
 
	@Value("${db.driver}")
	private String driver;

But the property placeholder ${} is unable to resolve in @Value, if print out the driver variable, it will display string ${db.driver} directly, instead of “oracle.jdbc.driver.OracleDriver”.

Solution

To resolve ${} in Spring @Value, you need to declare a STATIC PropertySourcesPlaceholderConfigurer bean manually. For example :

AppConfig.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@PropertySource("classpath:db.properties")
public class AppConfig {
 
	@Value("${db.driver}")
	private String driver;
	
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
		return new PropertySourcesPlaceholderConfigurer();
	}
}

For XML configuration, Spring will help you to register PropertySourcesPlaceholderConfigurer automatically.


<util:properties location="classpath:db.properties"/>
Note
Read this Spring JIRA SPR-8539
Note
You may interest at this Spring @PropertySource example

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
6 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Mantas Sinkevi?ius
7 years ago

It does not resolve a value if it’s declared as a field, but works if I pass it as a method parameter with @Value annotation. Any idea why this behavior could be happening?

David
6 years ago

Thanks for helping my track this down, BUT, see discussion at https://stackoverflow.com/questions/32715190/spring-util-properties-in-app-context-xml-file — you cannot use util.properties. Must use the instead

TRUMP
3 years ago

THANK YOU!!! THIS ARTICLE REALLY SOVLE MY PROBLEM!!!

Ayo
6 years ago

Thanks a lot… this just saved me

helper bro
6 years ago

Thank you very much Sir,
saved my day.

duqi
8 years ago