In this post, we will externalize the properties used in the application in a property file and will use PropertyPlaceHolderConfigurer
to resolve the placeholder at application 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 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.
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 @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 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.
No comments :
Post a Comment