Spring Boot DataSource Configuration Java Example
Now a days (Date: May 2017) almost all application which use Spring framework using Spring Boot and to connect data base using java as configuration class please use example below:
First you will have define database config in your properties file or YML file. I will be using YML file to keep data base configuration as below:
- Database.yml:
db: JAVAHONK_DS: driverClassName: oracle.jdbc.OracleDriver url: jdbc:oracle:thin:@javahonk.com:1521/java username: javahonk password: javahonk
Java class to read data base configuration and return jdbctemplate:
- JavaHonkDataSourceConfig.java:
package com.verizon.fcip; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; @Configuration // Below annotation automatically scans all the Services bound to // the application and converts them to datasources. //@ServiceScan public class JavaHonkDataSourceConfig { @Configuration static class CloudConfiguration { /** * Data Sources * */ @Bean(name = "javahonkDataSource") @Primary @ConfigurationProperties(prefix = "db.JAVAHONK_DS") public DataSource fcipDataSource() { return DataSourceBuilder.create().build(); } /** * Spring JDBC Templates * */ @Bean(name = "jdbcJavahonk") @Autowired public JdbcTemplate fcipJdbcTemplate(@Qualifier("javahonkDataSource") DataSource dsSlave) { return new JdbcTemplate(dsSlave); } } }
Note: To run this application Database.yml should be in your class-path and to get JDBCTemplate object you can use annotation as usual below is sample:
@Autowired
@Qualifier(“jdbcJavahonk”)
private JdbcTemplate jdbcTemplate;
Reference: Spring boot data base configuration