In a Spring Boot application, the application.properties (or application.yml) file is a central place that contains all configurations or settings of the application, in form of key-value pairs. And in this article, I’d love to share with you how to read or bind values of properties in Spring application configuration file in Java code.

 

1. Bind Property Values to Instance Variables

Spring provides the @Value annotation which can be used to bind value of a property to a field in a Spring component class. Given the following property declared in the application.properties file:

product.page.size=10
Then you can use @Value(“{property.name}”) to annotate a member variable (instance field) of a Spring component class, as shown below:

package net.codejava;

import org.springframework.beans.factory.annotation.Value;

@Service
public class ProductService {

	@Value("${product.page.size}")
	private Integer pageSize;
	

	public Page<Product> listAll(int pageNum) {
		
		Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
		
		return repo.findAll(pageable);
	}
	
}
Here, when an object of the ProductService class is created, its instance variable pageSize is initialized with the value read from the property named product.page.size which is declared in the application.properties file. It’s easy to use and convenient, right?

If no such property found, a java.lang.IllegalArgumentException will be thrown like this:

java.lang.IllegalArgumentException: Could not resolve placeholder 'product.page.size' in value "${product.page.size}"
You can bind to a String variable in a controller, as follows:

@Controller
public class AppController {
	
	@Value("${default.page.title}")
	private String defaultPageTitle;
	
	...
}
You can also read value of a property to a field in a @Configuration class:

@Configuration
public class MvcConfig implements WebMvcConfigurer {

	@Value("{product.view.name}")
	private String productViewName;
	
	...
}
And bind value of a property to a field in a @Component class:

@Component
public class DatabaseLoader {
	
	@Value("{sample.db.path}")
	private String sampleDatabasePath;

	...
}


 

Notes:

  • using @Value annotation in a non-Spring class has no effect. It can be used only in @Component, @Service, @Configuration classes
  • You can’t bind property value to a static variable
  • You can’t bind property value to a local variable


2. Bind Property Values to Arguments of Handler Method

You can also bind value of a property to a method parameter in a Spring MVC controller like this:

@Controller
public class AppController {
	
	@Autowired
	private ProductService service;
	
	@RequestMapping("/")
	public String viewHomePage(Model model, 
			@Value("${default.page.title}") String defaultPageTitle) {
		
		model.addAttribute("pageTitle", defaultPageTitle);
		
		// return view name...
	}
	
}
In this case, Spring reads property value from application configuration file and pass it as an argument of the handler method when it is invoked. Remember that you can use the @Value annotation in handler method of Spring MVC/REST controller only.


3. Read Properties using Environment object

You can use an Environment object provided by Spring application context to read value of a property from the application configuration file. Below is an example:

import org.springframework.core.env.Environment;

@Controller
public class AppController {
	
	@Autowired Environment env;
	
	@RequestMapping("/")
	public String viewHomePage(Model model) {
		
		String pageTitle = env.getProperty("default.page.title");
		
		model.addAttribute("pageTitle", pageTitle);
		
		// return view name...
	}
	
}
As the name implies, you can use Environment object to read system environment variables, for example:

String userHome = env.getProperty("user.dir");
Note that if there are 2 properties with the same name in application configuration file and in system environment variable, the system environment variable will override.


4. Map a set of properties to a JavaBean-style object

Spring framework provides the @ConfigurationProperties annotation which you can use to map a group of properties in the configuration file to a JavaBean object. Suppose that we have some properties sharing the same prefix “myapp” in the application.properties file as below:

myapp.title=Document Upload Lite
myapp.version=1.0.0
myapp.build=1234
Then code a JavaBean-style class as follows:

package net.codejava;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@ConfigurationProperties(prefix = "myapp")
@Configuration("appInfo")
public class AppInfo {
	private String name;
	private String version;
	private int build;

	// getters and setters are not shown for brevity...

}
Then you can auto-wire an instance of this class in a Spring component class as shown below:

@Controller
public class AppController {

	@Autowired AppInfo appInfo;
	
	@RequestMapping("/")
	public String viewHomePage(Model model) {
		
		System.out.println("App name: " + appInfo.getName());
		System.out.println("App version: " + appInfo.getVersion());
		System.out.println("App build number: " + appInfo.getBuild());
		
		// return view name...
	}
	
}
You see, it’s very convenient, isn’t it? You can easily map properties from application configuration file to JavaBean object.


5. Read Property Values in Thymeleaf template

In Thymeleaf view template, you can read value of a property using @environment object using the following syntax:

${@enviroment.getProperty(‘property.name’)}
For example, show a text with value read from a property:

<div>[[${@environment.getProperty('app.name')}]]</div>
Or:

<div th:text="${@environment.getProperty('app.name')}"></div>
So far in this article, you have learned several ways of reading properties values from Spring application configuration file. I hope you found it helpful. To see the coding in action, watch the following video:

 

Other Spring Boot Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment

   


Comments 

#2Nam2022-07-10 08:19
Hi Narendra,
Sorry that course is discontinued. I offer you choosing one of my courses on Udemy here: www.udemy.com/user/namhaminh/
Quote
#1Narendra2022-07-09 10:15
Thanks Nam for the detailed tutorial.I have been following you since 2019.Felt best java tutorials on the internet.
One Question : I had opted for Java email course in 2019.I have got few emails but not all. Have u stopped this course or some other reason.
Please let me know, waiting for your reply!!
Quote