Configure Datasource

In order to use Hibernate, Jdbc, or JPA similar persistence framework or tools, you have to configure a java.sql.DataSource for it.

Spring DataSource support is available in sring-jdbc. Added it into your pom.xml.

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
</dependency>

A simple DataSouce configuration looks like.

@Configuration
public class DataSourceConfig {

    @Bean
    public DataSource testDataSource() {
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName("com.mysql.jdbc.Driver");
        bds.setUrl("jdbc:mysql://localhost:3306");
        bds.setUsername("jdbc.username");
        bds.setPassword("jdbc.password");
        return bds;
    }

}

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.

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.

In DataSouce configuration, use Environment to fetch these properties.

Spring Jdbc provides a simple EmbeddedDatabaseBuilder to build an embedded datasource on the fly way.

Here we build an embedded H2 datasource.

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.

The complete codes of DataSouceConfig.

Three DataSouce beans are configured. Do not worry about the @Profile annotation, I will explain it in a Spring Profile related section for it.

Last updated

Was this helpful?