Spring @PropertySource example

spring-properties-example

In Spring, you can use @PropertySource annotation to externalize your configuration to a properties file. In this tutorial, we will show you how to use @PropertySource to read a properties file and display the values with @Value and Environment.

P.S @PropertySource has been available since Spring 3.1

1. @PropertySource and @Value

A classic example, read a properties file and display with ${}.

config.properties

mongodb.url=1.2.3.4
mongodb.db=hello
AppConfigMongoDB

package com.mkyong.config;

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

@Configuration
@ComponentScan(basePackages = { "com.mkyong.*" })
@PropertySource("classpath:config.properties")
public class AppConfigMongoDB {

	//1.2.3.4
	@Value("${mongodb.url}")
	private String mongodbUrl;

	//hello
	@Value("${mongodb.db}")
	private String defaultDb;

	@Bean
	public MongoTemplate mongoTemplate() throws Exception {

		MongoClientOptions mongoOptions = 
			new MongoClientOptions.Builder().maxWaitTime(1000 * 60 * 5).build();
		MongoClient mongo = new MongoClient(mongodbUrl, mongoOptions);
		MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, defaultDb);
		return new MongoTemplate(mongoDbFactory);

	}

	//To resolve ${} in @Value
	@Bean
	public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
		return new PropertySourcesPlaceholderConfigurer();
	}

}
Note
To resolve ${} in @Values, you must register a static PropertySourcesPlaceholderConfigurer in either XML or annotation configuration file.

2. @PropertySource and Environment

Spring recommends to use Environment to get the property values.

AppConfigMongoDB

package com.mkyong.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
//...

@Configuration
@ComponentScan(basePackages = { "com.mkyong.*" })
@PropertySource("classpath:config.properties")
public class AppConfigMongoDB {

	@Autowired
	private Environment env;

	@Bean
	public MongoTemplate mongoTemplate() throws Exception {

		String mongodbUrl = env.getProperty("mongodb.url");
		String defaultDb = env.getProperty("mongodb.db");
		
		MongoClientOptions mongoOptions = 
			new MongoClientOptions.Builder().maxWaitTime(1000 * 60 * 5).build();
		MongoClient mongo = new MongoClient(mongodbUrl, mongoOptions);
		MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongo, defaultDb);
		return new MongoTemplate(mongoDbFactory);

	}

}

3. More @PropertySource Examples

More common examples.

3.1 Example to resolve ${} within @PropertySource resource locations.


	@Configuration
	@PropertySource("file:${app.home}/app.properties")
	public class AppConfig {
		@Autowired
		Environment env;
	}

Set a system property during startup.


	System.setProperty("app.home", "test");

	java -jar -Dapp.home="/home/mkyon/test" example.jar

3.2 Include multiple properties files.


	@Configuration
	@PropertySource({
		"classpath:config.properties",
		"classpath:db.properties" //if same key, this will 'win'
	})
	public class AppConfig {
		@Autowired
		Environment env;
	}
Note
If a property key is duplicated, the last declared file will ‘win’ and override.

4. Spring 4 and @PropertySources

Some enhancements on Spring 4.

4.1 Introduces new @PropertySources to support Java 8 and better way to include multiple properties files.


	@Configuration
	@PropertySources({
		@PropertySource("classpath:config.properties"),
		@PropertySource("classpath:db.properties")
	})
	public class AppConfig {
		//...
	}

4.2 Allow @PropertySource to ignore the not found properties file.


	@Configuration
	@PropertySource("classpath:missing.properties")
	public class AppConfig {
		//...
	}

If missing.properties is not found, the system is unable to start and throws FileNotFoundException


	Caused by: java.io.FileNotFoundException: 
		class path resource [missiong.properties] cannot be opened because it does not exist

In Spring 4, you can use ignoreResourceNotFound to ignore the not found properties file


	@Configuration
	@PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)
	public class AppConfig {
		//...
	}

        @PropertySources({
		@PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true),
		@PropertySource("classpath:config.properties")
        })

Done.

References

  1. Sprong IO – PropertySource
  2. Spring IO – PropertySources
  3. Spring IO – Configuration
  4. Spring @Value default value
  5. Spring JIRA : SPR-8539

About the Author

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

Comments

avatar
20 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
20 Comment authors
eviltoadmaheshbabuasdadKathTiya Recent comment authors
newest oldest most voted
Tiya
Guest
Tiya

Can you write a tutorial on org.springframework.core.env.Environment along with @ConfigurationProperties

Daniel
Guest
Daniel

Hi, How to load properties file dynamically and use getKeys() from resource bundle. I don’t want to load did using getBundle() method. Please suggest.

Mani Kiran
Guest
Mani Kiran

I have an odd situation where a class annotated with Configuration had two Bean methods. One method created a DataSource and the other a PropertySourcesPlaceholderConfigurer that I initialized from property files that I located based on values in the Autowired Environment field. That worked fine (environment was initialized before configurer was initialized). I decided to move the properties method into another class along with the Environment field and, once I did that, Environment isnull when the configurer bean is initialized.

Can anyone please help me to solve this…

Thank you

Sai
Guest
Sai

Thanq so much for your post, it very help full.

I have a doubt in “2.@PropertySource and Environment” in this how to point to “Profile-specific application properties” ?

For Example, i have given Db details of Dev, QA and Prod in 3 property files as follows

application-dev.properties
application-qa.properties
application-prod.properties

and generic one application.properties file in this i have given “spring.profiles.active=dev”

But when i sued @PropertySource , its expecting application-dev.properties instead of application.properties file. can you tell me how to solve this.

Thanks,
Sai

Om Jai
Guest
Om Jai

Thanks for this example.
My requirement is the read the property file configured as URL resource in websphere 8. So instead of “classpath:config.properties” how can I refer to URL resource JNDI name??

According to the documentation here http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html I have to put “java:comp/env/”

eviltoad
Guest
eviltoad

As always, thank you very much… I was missing the PropertySourcesPlaceholderConfigurer and couldn’t figure out why my unit test configuration was not resolving the placeholders.

maheshbabu
Guest
maheshbabu

@Component
@Configuration
@PropertySource(“classpath:mapping.properties”)
Class MappingClass{

@Value(“${lineName}”)
private String lineName; /// here null is coming

}

// mapping.properties file
lineName = one

Could any one suggest what is the issue

asdad
Guest
asdad

nice

Kath
Guest
Kath

is it possible to access all the values of property file and populate it in a hash map? like make it as a key value pair

John
Guest
John

Thank you very much for your job and simple explanations! =)

Pranav
Guest
Pranav

Hi,

My scenario is I am using some external jar as a maven dependency in my project which in turns requires some properties. When I am using @PropertySource I am able to pick up those values in my project but not in dependent project
Any suggestions???

Dusan Odalovic
Guest
Dusan Odalovic

Thanks for the post.
You should correct the typo

To resolve ${} in @Values, you must register a …
….
@Values should be @Value of course

Jesse Zhou
Guest
Jesse Zhou

How would you use the properties in another class?

Jason
Guest
Jason

Always relieved to see this blog pop up in Google results. Consistently useful and accurate info. Thanks!

Savani
Guest
Savani

Hey, Do you’ve any idea how we can load the .properties file junit and can use properties set against those values?

Zilev
Guest
Zilev

wonderful job, thanks a lot, this post were to helpful to me :)

Maxi Wu
Guest
Maxi Wu

thank you. I want to ask, if the code is like @Value(“#properties[‘foo.bar’]}”) String arg0 inside @Controller constructor, what does this mean? how does this relate to your example here?

Rohit More
Guest
Rohit More

I afraid when I changed value in property file but @value annotation takes old value only. For accepting new changes it should reload the PropertySourcesPlaceholderConfigurer Bean. but stuck with this how to reload property file and initialize new values with the keys?

Zoran I.
Guest
Zoran I.

Just a note for anyone who wants to use yaml instead of regular property files. Yaml unfortunately can’t be loaded via @PropertySource Annotation. However, I added in property place holder configurer yaml property factory bean and loaded yaml that way and then set properties on the configurer. The @PropertySource was removed but the value were set the usual way. Dependencies were snakeyaml jar and spring boot.

Miral
Guest
Miral

Hi, looking forward for example, where we can use custom property resolver. e.g. I have third party system where all properties resides, need a way to tell spring boot to resolve all properties from my custom class that will read from other services. How to register custom property resolver to read props rather than reading from application.properties.