Here, I uses Apache Commons Dbcp's BasicDataSource to build a DataSource. It is configured for MySQL database, before use it, do not forget to add mysql driver into pom.xml.
Declares this configuration class in getRootConfigClasses method of AppInitializer.
In above codes, we set username, password etc in hard codes, but in a real application, it is better to externalize these configurations into a property file.
Create another @configuration class for this purpose.
@Configuration@ComponentScan( basePackageClasses = {Constants.class}, excludeFilters = { @Filter( type =FilterType.ANNOTATION, value = {RestController.class,ControllerAdvice.class,Configuration.class } ) })@PropertySource("classpath:/app.properties")@PropertySource(value ="classpath:/database.properties", ignoreResourceNotFound =true)publicclassAppConfig {}
AppConfig work as an entr configuration for this application. @ComponentScan use a fitler to load all none web components.
Use @PropertySource to load the external properties files, app.properties is use for application properties, and database.properties for holding database datasource properties.
An embedded datasource is every helpful for development stage, everytime when we run the application, or run the tests, we are getting a fresh runtime environment.
Spring Jdbc also provides other built-in DataSource, such as DriverManagerDataSource, and some application server specific DataSource, eg. for Webphere.
For a production runtime environment, we should use pooled datasource, such as Apache Commons Dbcp, or application server built-in DataSource to get better performance.
We have discussed the usages of Apache Commons Dbcp earlier, you can add extra pool configuration for this datasource.
For application server built-in DataSource, Spring can access it via a Jndi proxy. Firstly configure a Jndi DataSource in appliation server GUI, then defines JndiObjectFactoryBean to access it via Jndi name.