1. 程式人生 > >Spring Boot Druid 資料來源配置解析

Spring Boot Druid 資料來源配置解析

1、資料來源配置屬性類原始碼

package org.springframework.boot.autoconfigure.jdbc;

@ConfigurationProperties(
    prefix = "spring.datasource"
)
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
    private ClassLoader classLoader;
    private String name;
    private boolean
generateUniqueName; private Class<? extends DataSource> type; private String driverClassName; private String url; private String username; private String password; private String jndiName; private DataSourceInitializationMode initializationMode; private String platform;
private List<String> schema; private String schemaUsername; private String schemaPassword; private List<String> data; private String dataUsername; private String dataPassword; private boolean continueOnError; private String separator; private Charset sqlScriptEncoding;
private EmbeddedDatabaseConnection embeddedDatabaseConnection; private DataSourceProperties.Xa xa; private String uniqueName; ...... }

詳見Spring Boot 2.1.0文件

 

2、註解注入資料來源型別

@Configuration
public class MyConfig {
    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSource dataSource() {
    //對應DataSourceConfiguration類下的幾個型別
//javax.sql.DataSource (Generic) //BasicDataSource (Dbcp2) //HikariDataSource (Hikari) //org.apache.tomcat.jdbc.pool.DataSource (tomcat) return DataSourceBuilder.create().type(DataSource.class).build(); } }

 

3、配置

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/springboot?useSSL=false
    username: root
    password: xiaochao
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: org.apache.tomcat.jdbc.pool.DataSource
    initialization-mode: ALWAYS
    schema-username: root
    schema-password: xiaochao
    schema:
      - classpath:schema.sql
    data-username: root
    data-password: xiaochao
#    hikari:
#      username: root
#      password: xiaochao
#      jdbc-url: jdbc:mysql://localhost:3306/springboot?useSSL=false
#      driver-class-name: com.mysql.cj.jdbc.Driver
#      schema:
#        - classpath:schema.sql
server:
  port: 1234

 

注意:schema.sql 沒有生效,待解!!!