Spring Framework - What is PropertyPlaceHolderConfigurer?

We will start with Configurating PropertyPlaceHolderConfigurer to use classpath to search for properties file and define DBProperties class which uses ${...} to refer to those properties and at last will test the configurations.

1. Java Configuration for PropertyPlaceHolderConfigurer

public class AppConfig {

public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setLocations(new ClassPathResource("application-db.properties"));
return propertySourcesPlaceholderConfigurer;

We created object of PropertySourcesPlaceholderConfigurer and set the Locations to search. In this example we used ClassPathResource to resolve the properties file from classpath. You can use file based Resource which need absolute path of the file.

2. DBProperties class using properties

public class DBProperties {

private String userName;

private String password;

private String url;

//getters for instance fields

We used @Value annotation to resolve the placeholders.

3. Testing the configuration

public class Main {
private static final Logger logger = Logger.getLogger(Main.class.getName());

public static void main(String[] args) {
try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class, DBProperties.class);) {
DBProperties dbProperties = context.getBean(DBProperties.class);
logger.info("This is dbProperties: " + dbProperties.toString());

For testing, we created object of AnnotationConfigApplicationContext and got DBProperties bean from it and logged it using Logger. This is the simple way to externalize the configuration properties from framework congfiguration. You can also get the full example code from Github.

Tags: Spring Framework, Spring Core PropertyPlaceHolderConfigurer

← Back home