Spring Core: Reading properties with PropertyPlaceHolderConfigurer
PropertyPlaceHolderConfigurer is a handy way to externalize the properties you want to use in a property file so that they're still resolved when starting the app.
Join the DZone community and get the full member experience.
Join For FreeIn this post, we will externalize the properties used in an application in a property file and will use PropertyPlaceHolderConfigurer
to resolve the placeholder at startup time.
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 an object of PropertySourcesPlaceholderConfigurer
and set the locations to search. In this example, we used ClassPathResource to resolve the properties file from the classpath. You can use a file-based resource, which needs the absolute path of the file.
DBProperties File
@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 the @Value
annotation to resolve the placeholders.
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 an object of AnnotationConfigApplicationContext
and got theDBProperties
bean from it and logged it using Logger. This is a simple way to externalize the configuration properties from framework configuration. You can also get the full example code from GitHub.
Published at DZone with permission of Gaurav Rai Mazra, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments