Spring Boot DataSource的建立方法

摘要

看完本文你將掌握以下知識點:mysql

  1. Spring Boot項目中DataSource的建立方法

DataSource的建立方法

前面講了不少Spring Boot數據訪問方面的內容,在講到本身擴展數據訪問的時候,示例代碼中給出的DataSource建立方式都是DriverManagerDataSource,好比:spring

#datasource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/springboot1?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=newpwd
@Value("${spring.datasource.driver-class-name}")
    String driverClass;
    @Value("${spring.datasource.url}")
    String url;
    @Value("${spring.datasource.username}")
    String userName;
    @Value("${spring.datasource.password}")
    String passWord;

    @Bean(name = "dataSource")
    public DataSource dataSource() {

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);
        return dataSource;
    }

若是有多個數據源,就再建立多個DriverManagerDataSource
通常生產項目中咱們不會這樣使用,一般能夠使用org.apache.commons.dbcp.BasicDataSourcesql

實際上Spring Boot爲咱們提供了簡便的建立DataSource的方法:apache

#datasource
#須要執行數據源的類型
spring.datasource.ds1.type=org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.ds1.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.ds1.url=jdbc:mysql://localhost:3306/springboot1?useUnicode=true&characterEncoding=utf-8
spring.datasource.ds1.username=root
spring.datasource.ds1.password=newpwd

spring.datasource.ds2.type=org.apache.tomcat.jdbc.pool.DataSource
spring.datasource.ds2.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.ds2.url=jdbc:mysql://localhost:3306/springboot2?useUnicode=true&characterEncoding=utf-8
spring.datasource.ds2.username=root
spring.datasource.ds2.password=newpwd
@Bean(name = "dataSource1")
    //application.properties中屬性名稱的前綴
    @ConfigurationProperties(prefix = "spring.datasource.ds1")
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "dataSource2")
    @ConfigurationProperties(prefix = "spring.datasource.ds2")
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }

目前,此種方式支持以下幾種數據源類型:tomcat

"org.apache.tomcat.jdbc.pool.DataSource", "com.zaxxer.hikari.HikariDataSource", "org.apache.commons.dbcp.BasicDataSource", "org.apache.commons.dbcp2.BasicDataSource"springboot

使用哪一種數據源類型,就要在項目中加入相應的jar依賴,
好比org.apache.tomcat.jdbc.pool.DataSourceapp

<dependency>
    <groupId>org.apache.tomcat</groupId>
    <artifactId>tomcat-jdbc</artifactId>
    <version>8.5.6</version>
</dependency>
相關文章
相關標籤/搜索