spring全家桶使用学习-jdbc自动装配(单数据源配置)
相关代码示例:
使用springboot 自动配置jdbc单数据源 : https://github.com/mengyan183/spring-family/tree/main/spring-datasource
使用spring-framework 手动实现 jdbc 单数据源管理: https://github.com/mengyan183/spring-family/tree/main/spring-datasource-without-autoconfig
对于spring-boot-jdbc-starter 完成spring-jdbc 自动装配相关
自动装配主要包含 :对于自动装配,如果手动自定义声明相关bean,则自动装配处理已声明的bean;属于按需分配
- DataSourceAutoConfiguration 配置 DataSource
- DataSourceTransactionManagerAutoConfiguration 自动配置 DataSourceTransactionManager
- JdbcTemplateAutoConfiguration 自动配置 JdbcTemplate
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!--引入jdbc连接--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--引入 h2 数据库连接驱动--> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
可以通过 actuator 查看自动装配的相关beans
https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready
对于actuator 支持 web/jmx 两种请求方式,对于web模式中两个默认开启的 断点(endpoint), info/health
对此需要注意的一点为:
由于默认情况下 management.endpoints.web.exposure.include = info,health 只开放了两个节点, 需要访问beans 时, 可以写成 management.endpoints.web.exposure.include=info,health,beans 或者 management.endpoints.web.exposure.include=*
访问 web请求根路径/actuator/beans 可以看到所有接受spring 容器管理的bean
关于 spring-datasource-init 操作
spring-framework datasource sql init 相关
https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#jdbc-initializing-datasource
https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto-initialize-a-database-using-spring-jdbc
https://docs.spring.io/spring-boot/docs/2.0.0.M7/reference/html/howto-database-initialization.html
相关配置包含
# 初始化模式 包含 embedded/always/never
spring.datasource.initialization-mode=
# 指定sql平台
spring.datasource.platform=
可选操作: 如果不指定sql文件路径,会自动查找classpath下根据 platform配置 并查找指定的sql文件 文件类型为 schema-{platform(sql平台)}.sql data-{platform}.sql
# 初始化执行 schema sql
spring.datasource.shcema=指定schema sql文件地址
# 初始化执行 data sql
spring.datasource.data=指定data sql文件地址