Spring provides @Profile annotation to declare beans for specific profiles. You can specify a spring.profiles.active environment varible to activiate which beans will be used in Spring applications.
In this sample application, I would like use Maven profile to specify the spring.profiles.active for different development stage.
For development stage, I would like an embeded database, such as H2. It is easy to user, and start up with a clean environment for test, I also like enable logging debug and get more log info.
For staging stage, I would like use similar environment with produciton to run the application with a CI server, such as Jenkins, Travis CI, Circle CI etc.
For produciton, enable all cache and performance optimization, use application server container managed datasource, only enable essential logging tracking etc.
In every Maven profiles, there is a spring.profiles.active property, its value will be filled in applicaiton.properties file and replaces the placeholder @spring.profiles.active@ in this file, the properties files can be categoried in different files for varied purposes, such as database connection, global application settings etc. They are placed in the profile specific resource folder(defined in resources element in every profiles section).
Append a -P parameter to switch which Maven profile will be applied. eg.
mvn clean package -Pprod
The above command will package the applicatin for prod profile, it also apply spring.profiles.active value(prod) for this application when it is running.
For exmaple, for the DataSource configuration in DataSourceConfig, the @Profile("prod") annotated bean will be activated.
@Bean
@Profile("prod")
public DataSource prodDataSource() {
JndiObjectFactoryBean ds = new JndiObjectFactoryBean();
ds.setLookupOnStartup(true);
ds.setJndiName("jdbc/postDS");
ds.setCache(true);
return (DataSource) ds.getObject();
}
It uses the application server container managed DataSource for better performance and also easy to be monitored by application server console. Tomcat, Glassfish, Weblogic all provide friendly UI for administration.