avatar

Spring02连接池&注解开发&集成Junit

配置数据库连接池

连接池相关知识点

作用

减少频繁创建、频繁释放链接、提高效率

常见的连接池

DBCP,C3P0,Druid

创建连接池

导入spring、数据库和连接池依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>

创建C3p0连接池

1
2
3
4
5
6
7
8
9
10
11
12
@Test
//测试手动创建 c3p0 数据源
public void test1() throws Exception {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUser("root");
dataSource.setPassword("root");
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}

思考

如何把ComboPooledDataSource对象的创建交给Spring

创建Druid连接池

1
2
3
4
5
6
7
8
9
10
11
12
@Test
//测试手动创建 druid 数据源
public void test2() throws Exception {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
DruidPooledConnection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}

思考

如何把DruidDataSource对象的创建交给Spring

Spring管理连接池步骤

添加spring、数据库和连接池依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>

添加jdbc.properties

注意:key的值必须要写前缀,不然可能解析不了

1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

在spring配置中引入jdbc.properties

注意:必须先引入context命名空间

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--在spring的配置文件中引入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>

</beans>

在spring配置中添加连接池配置信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!--在spring的配置文件中引入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!--在spring的配置文件中添加连接池配置信息-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>

</beans>

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package cn.itcast;

import com.alibaba.druid.pool.DruidDataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;

public class C3p0Test {
@Test
public void test1() throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource)context.getBean("dataSource");
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}

注解开发

开启注解扫描

1
<context:component-scan base-package="cn.itcast"></context:component-scan>

注解分类

bean相关注解1

以下注解的功能用于标记指定的类的对象交给spring管理

注解 描述
@Component 使用在类上用于实例化Bean
@Controller 使用在web层类上用于实例化Bean
@Service 使用在service层类上用于实例化Bean
@Repository 使用在dao类上用于实例化Bean

使用方式1:bean的名字显示指定

1
2
3
4
@Repository("userDaoImpl")
public class UserDaoImpl implements UserDao{

}

使用方式2:bean的名字由框架默认设置,省略bean的名字,bean的名字默认是当前类的名字首字母小写,代码中这个bean的名字其实就是userDaoImpl

1
2
3
4
@Repository
public class UserDaoImpl implements UserDao{

}

Bean相关注解2(了解)

注解 描述
@Primary 设置类对应的bean按类型装配时优先装配,,比如如果有多个dao实现类,service要根据类型注入,为了提高dao的优先级,可以在类上加该注解
@DependsOn 控制bean的加载顺序,使其在指定bean加载完毕后再加载
@Order 控制配置类的加载顺序
@Lazy 控制bean的加载时机,使其延迟加载

@Primary

位置:类定义上方

作用:设置类对应的bean按类型装配时优先装配

范例:

1
2
@Primary
public class ClassName{}
  • 说明:

    • @Autowired默认按类型装配,当出现相同类型的bean,使用@Primary提高按类型自动装配的优先级,多个@Primary会导致优先级设置无效

      1592545826198

依赖加载

(1)@DependsOn

类型:类注解、方法注解

位置:bean定义的位置(类上或方法上)

作用:控制bean的加载顺序,使其在指定bean加载完毕后再加载

范例:

1
2
3
@DependsOn("beanId")
public class ClassName {
}

说明:

​ 配置在方法上,使@DependsOn指定的bean优先于@Bean配置的bean进行加载

​ 配置在类上,使@DependsOn指定的bean优先于当前类中所有@Bean配置的bean进行加载

​ 配置在类上,使@DependsOn指定的bean优先于@Component等配置的bean进行加载

​ 相关属性

value(默认):设置当前bean所依赖的bean的id

@Order

类型:配置类注解

位置:配置类定义的位置(类上)

作用:控制配置类的加载顺序

范例:

1
2
3
@Order(1)
public class SpringConfigClassName {
}

@Lazy

类型:类注解、方法注解

位置:bean定义的位置(类上或方法上)

作用:控制bean的加载时机,使其延迟加载

范例:

1
2
3
@Lazy
public class ClassName {
}

依赖加载应用场景

@DependsOn

  • 微信订阅号,发布消息和订阅消息的bean的加载顺序控制

  • 双11活动期间,零点前是结算策略A,零点后是结算策略B,策略B操作的数据为促销数据。策略B加载顺序与促销数据的加载顺序

@Lazy

  • 程序灾难出现后对应的应急预案处理是启动容器时加载时机

@Order

  • 多个种类的配置出现后,优先加载系统级的,然后加载业务级的,避免细粒度的加载控制

依赖注入相关注解

以下注解作用在属性上,完成对属性值的注入

注解 描述
@Autowired 使用在成员变量上,会根据类型依赖注入。
@Qualifier 结合@Autowired一起使用,根据名称依赖注入
@Resource 相当于@Autowired+@Qualifier,按照名称进行注入,JDK1.9之后不能使用
@Value 注入普通属性

注意1

@Resource(name=”bean名”)在JDK1.9中使用后无法注入,不建议使用

注意2

Autowired根据类型匹配,换句话说就是一个接口如果有多个实现类就必须配合Qualifier一起使用了

注意3

Qualifier必须配合@Autowired一起使用,当某个接口的实现类有多个的时候配合该注解使用

1592545895441

配置单例和多例注解

注解 描述
@Scope 标注Bean的作用范围,该注解配合@Component,@Controller,@Service,@Repository使用

生命周期相关注解

注意:以下注解JDK1.9不能用

注解 描述
@PostConstruct 该注解标注在方法上,该方法会在Bean创建的时候执行
@PreDestroy 该注解标注在方法上,该方法会在Bean销毁的时候执行

替换applicationContext相关注解

注解 描述
@Configuration 替换applicationContext.xml文件
@ComponentScan 替换包扫描context:component-scan
@Bean 替换bean标签
@PropertySource 替换<context:property-placeholder location=”classpath:jdbc.properties”>
@Import 替换<import resource="xxx.xml"></import>标签导入其他的configuration

全注解开发步骤

1.编写专门操作数据库的相关配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.itheima.cofig;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;

@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {

@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;

@Bean("dataSource") //替代<bean id="dataSource">
public DataSource getDataSource() throws PropertyVetoException {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}

}

2.编写替换applicationContext.xml的类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.itheima.cofig;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

//标志该类是Spring的核心配置类
@Configuration
//<context:component-scan base-package="com.itheima"/>
@ComponentScan("com.itheima")
//<import resource=""/>
@Import({DataSourceConfiguration.class})
public class SpringCofiguration {

}

3.编写测试方法

1
2
3
4
5
6
public static void main(String[] args) {
//ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext app = new AnnotationConfigApplicationContext(SpringCofiguration.class);
UserService userService = app.getBean(UserService.class);
userService.save();
}

注意事项

1.@Bean注解必须给一个bean的名字

2.SpringCofiguration是主配置文件,引入了DataSourceConfiguration配置,所以在DataSourceConfiguration类上可以省略@Configuration注解,该注解在主配置文件配置一次就够了,当然每个配置文件都配置也没有任何问题

注解方式和XML方式配置对比

集成junit

为什么要集成junit

1.每次需要手动加载配置文件创建ApplicationContext对象

2.调用getBean方法获取bean

3.getBean方法返回的是Object对象,需要强转

集成junit的好处

可以直接将我们要使用的bean注入到当前测试类

使用方式

引入依赖

注意junit版本要大于等于4.12,否则会报如下错误

1
2
3
4
5
6
7
8
9
10
11
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>

junit测试类上加注解

注解功能

@RunWith是个运行器,SpringJUnit4ClassRunner表示运行在Spring的开发环境中,里面自带applicationContext,所以加上该注解后不需要手动创建applicationContext对象

@ContextConfiguration指定要读取的配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.itheima.test;

import com.itheima.cofig.SpringCofiguration;
import com.itheima.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.SQLException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {

}

在测试类中注入要使用的bean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package com.itheima.test;

import com.itheima.cofig.SpringCofiguration;
import com.itheima.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.SQLException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")//导入XML版配置文件
//@ContextConfiguration(classes = {SpringConfig.class})//导入注解版配置文件
public class SpringJunitTest {

@Autowired
private UserService userService;//测试使用

@Autowired
private DataSource dataSource;//测试使用

@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}

}

Spring整合MyBatis

点击查看

面试题

BeanFactory和FactoryBean的区别

  • FactoryBean:封装单个bean的创建过程,提供了了一些方法比如获取当前bean,判断是否是单例,获取当前bean的类型。目的是为了创建某些复杂的bean
  • BeanFactory:Spring容器顶层接口,定义了bean相关的获取操作
文章作者: 微信:hao_yongliang
文章链接: https://haoyongliang.gitee.io/2020/01/16/spring/Spring02%E8%BF%9E%E6%8E%A5%E6%B1%A0&%E6%B3%A8%E8%A7%A3%E5%BC%80%E5%8F%91&%E9%9B%86%E6%88%90Junit/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 郝永亮的主页
打赏
  • 微信
    微信
  • 支付寶
    支付寶

评论