学习目录
1. 具体的配置和测试
SprimgBoot版本是2.3.4;在下面的配置文件中URL是必须要指定时区的,如果不指定时区就会报错;
spring:
datasource:
username: root
password: XXXXXXX
url: jdbc:mysql://localhost:3306/library?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
#用来表示可以加在的类似于上面的默认配置文件位置;
schema: #文件名等,而且是个list数组,在前面介绍过list的用法;
#如下是指classpath目录下的文件datasource.sql;
- classpath: datasource.sql
-
下面这个类DataSourceProperties
就是SpringBoot中用来指定datasource的类,它提取配置文件中以spring.datasource开头的配置信息,然后在类中设置好,属于一些连接数据库用的配置;
@ConfigurationProperties(prefix = "spring.datasource")
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {}
为了更好的理解,放一个测试时方法,试一下是否能连接成功
:
@Autowired
DataSource dataSource;
@Test
void contextLoads() {
try {
System.out.println("看看地址"+dataSource);
Connection connection = dataSource.getConnection();
System.out.println(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
运行后的结果就如下图,SpringBoot2.x版本是通过HikariDataSource
运运行的;和1.x版本不一样(Tomcat.jdbc.pool.DataSource);
在配置文件里面也可以通过type更换数据源;这个可以在类DataSourceAutoConfiguration
里面看到;
@ConditionalOnProperty(prefix = "spring.datasource", name = "type")
static class ExplicitType {
}
下面是配置文件的具体使用;
#更换连接池;
spring:datasource:
type: org.springframework.jdbc.datasource.DriverManagerDataSource
更换后再次运行之前的测试方法,就会发现:
在类DataSourceConfiguration
中,有如下的判断,进行数据源的交换,问题是要有相关的jar包;
2. 在SpringBoot中的默认sql资源文件名
以下所有代码都属于
SpringBoot2.3.4
;
首先是在类DataSourceInitializer
,作为数据源初始化器;其中就对SQL资源文件的路径进行了初始化;
void initSchema() {
//就是这一条语句的getScripts()方法引入一些文件;
List<Resource> scripts = getScripts("spring.datasource.data", this.properties.getData(), "data");
//判断是否为空,大致属于日志提示;
if (!scripts.isEmpty()) {
if (!isEnabled()) {
logger.debug("Initialization disabled (not running data scripts)");
return;
}
String username = this.properties.getDataUsername();
String password = this.properties.getDataPassword();
runScripts(scripts, username, password);
}
}
从上面的getscript()方法进去之后,就可以看到如下源码吗了;
private List<Resource> getScripts(String propertyName, List<String> resources, String fallback) {
if (resources != null) {
return getResources(propertyName, resources, true);
}
String platform = this.properties.getPlatform();
List<String> fallbackResources = new ArrayList<>();
//其中platform的默认值是"all"
fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
fallbackResources.add("classpath*:" + fallback + ".sql");
//然后运行
return getResources(propertyName, fallbackResources, false);
}
上面的platform这个变量可以去类DataSourceProperties
里面查看;
/**
* Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or
* data-${platform}.sql).
*/
private String platform = "all";
从上面的介绍就可以看出来platform存放的位置主要是在:schema-${platform}.sql 和 data-${platform}.sql;
再结合上面的代码,就更好理解,
"classpath*:" + fallback + "-" + platform + ".sql"
"classpath*:" + fallback + ".sql"
在类DataSourceInitializerInvoker
中有这样一段介绍这两种文件,虽然看到不是很了解,还是记录下来;
/**
* Bean to handle {@link DataSource} initialization by running {@literal schema-*.sql} on
* {@link InitializingBean#afterPropertiesSet()} and {@literal data-*.sql} SQL scripts on
* a {@link DataSourceSchemaCreatedEvent}.
*/
当然如果想要在启动的SpringBoot的时候总是要这些sql脚本生效,那么需要在配置文件中进行如下配置,否则可能无法生效;
spring:
datasource:
initialization-mode: always
3. 在SpringBoot中使用Druid连接池
Druid连接池是一种常见的高性能的连接池;下面介绍一下如何在SpringBoot中进行使用;
3.1 更换为Druid
首先要先在pom.xml里面添加启动Druid的依赖;如下:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.24</version>
</dependency>
3.2 在配置文件中进行配置
如下:
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
当然除了上面的配置,还有一些url,name,password等连接数据库的基本配置是必须要有的,最后还有一些额外的与Druid相关的配置可以自己去进行查找,或者看官方介绍;
在官方介绍中不仅介绍了如何通过配置文件进行设置Druid的部分属性,
而且介绍了如何配置Filter,
介绍很多,需要就去看;
3.3 当然除了上面使用配置文件,还可以使用配置类来进行配置
@Configuration
public class DruidConfig {
//在这里的时候将配置文件里面的配置绑定到这个对象里面;
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
DataSource druid(){
return new DruidDataSource();
}
//配置一个servlet
@Bean
public ServletRegistrationBean statViewservlet(){
//这里就像是一个Servlet一样,也是用来处理指定的请求的,下面是处理druid下的所有请求;
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> map = new HashMap<>();
map.put("","");//这里放入需要的配置;
bean.setInitParameters(map);//将含有配置的map放入初始方法;
return bean;
}
//配置一个filter
public FilterRegistrationBean webStatFilter(){
//下面map可以设置的属性在类WebStatFilter里面;
FilterRegistrationBean filter = new FilterRegistrationBean(new WebStatFilter());
Map<String,String> map = new HashMap<>();
//比如下面是拦截器取消某些url拦截的写法,下面取消拦截/df;
map.put("exclusions","/df");//这里放入需要的配置;
filter.setInitParameters(map);
//设置filter的过滤url地址;放入数组;
filter.setUrlPatterns(Arrays.asList("/*"));
return filter;
}
}
配置完上面的类之后,如果需要多访问数等数据进行查看,在本机的话可以使用地址 http://localhost:8080/druid/index.html
,