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

@Configuration
public class AppConfig {

@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setLocations(new ClassPathResource("application-db.properties"));
//propertySourcesPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
//propertySourcesPlaceholderConfigurer.setIgnoreResourceNotFound(true);
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

@Configuration
public class DBProperties {

@Value("${db.username}")
private String userName;

@Value("${db.password}")
private String password;

@Value("${db.url}")
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