SpringBoot1.5.10的JDBC自动配置原理

创建SpringBoot的JDBC项目

pom.xml中导入的依赖:

<!--jdbc-->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
  </dependency>
  <!--web-->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
<!--mysql-->
 <dependency>
     <groupId>mysql</groupId>
     <artifactId>mysql-connector-java</artifactId>
     <scope>runtime</scope>
 </dependency>

在SpringBoot1.5.10版本中,在配置文件中不需要设置时区。

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8
    # &serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver

默认使用org.apache.tomcat.jdbc.pool.DataSource作为数据源:
在这里插入图片描述
数据源的相关配置都在DataSourceProperties类中:
在这里插入图片描述

JDBC的自动配置原理

org.springframework.boot.autoconfigure.jdbc下:

【1】在DataSourceConfiguration中,包含了很多可以配置创建的数据源,默认使用的是Tomcat连接池。另外,还可以通过spring.datasource.type指定数据源。

① SpringBoot中默认可以支持的数据源

org.apache.commons.dbcp2.BasicDataSource
org.apache.commons.dbcp.BasicDataSource
com.zaxxer.hikari.HikariDataSource
rg.apache.tomcat.jdbc.pool.DataSource
使用spring.datasource.type可以指定自定义的数据源,如:druid、c3p0等

② 使用spring.datasource.type指定自定义的数据源,值为数据源的全类名

 @ConditionalOnMissingBean({DataSource.class})
    @ConditionalOnProperty(
        name = {"spring.datasource.type"}
    )
    static class Generic {
        Generic() {
        }

        @Bean
        public DataSource dataSource(DataSourceProperties properties) {
        //利用DataSourceBuilder创建数据源:利用反射创建相应type类型的数据源,并且绑定相关属性
            return properties.initializeDataSourceBuilder().build();
        }
    }
//====================================================
  public DataSource build() {
        Class<? extends DataSource> type = this.getType();
        DataSource result = (DataSource)BeanUtils.instantiate(type);
        this.maybeGetDriverClassName();
        this.bind(result);
        return result;
    }

【2】DataSourceAutoConfiguration类中的DataSourceInitializer
在这里插入图片描述
DataSourceInitializer是一个ApplicationListener,作用:

runSchemaScripts();运行建表语句

@PostConstruct
public void init() {
	if (!this.properties.isInitialize()) {
		logger.debug("Initialization disabled (not running DDL scripts)");
		return;
	}
	if (this.applicationContext.getBeanNamesForType(DataSource.class, false,false).length > 0) {
			this.dataSource = this.applicationContext.getBean(DataSource.class);
	}
	if (this.dataSource == null) {
		logger.debug("No DataSource found so not initializing");
		return;
	}
	runSchemaScripts();
}

runDataScripts();运行插入数据的语句

@Override
public void onApplicationEvent(DataSourceInitializedEvent event) {
	if (!this.properties.isInitialize()) {
		logger.debug("Initialization disabled (not running data scripts)");
		return;
	}
	// NOTE the event can happen more than once and
	// the event datasource is not used here
	if (!this.initialized) {
		runDataScripts();
		this.initialized = true;
	}
}

  按一定的规则命名文件,就会在运行程序的同时自动执行sql文件中的语句:

默认规则:建表 schema-*.sql;数据相关data-*.sql
使用schema(建表)/data(数据)指定要执行的文件位置
spring:
  datasource:
    schema:
      - classpath:user.sql
	private String platform = "all";

	/**
	 * Schema (DDL) script resource references.
	 */
	private List<String> schema;
	/**
	 * Data (DML) script resource references.
	 */
	private List<String> data;

操作数据库

SpringBoot里面也自动配置了JdbcTemplate操作数据库:

在这里插入图片描述

举例使用:

@RestController
public class HelloController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("/hello")
    public List<Map<String,Object>> geuUser(){
        String sql = "select * from user";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值