IOC & AOP & Spring JDBC Template & 声明式事 务
务)
IOC
一、Spring概述
1.Spring是什么
Spring是分层的Java SE/EE应用 full-stack(全栈式) 轻量级开源框架。
提供了表现层 SpringMVC和持久层 Spring JDBC Template以及 业务层 事务管理等众多的企业级应用技术,还能整合开源世界众多著名的第三方框架和类库,逐渐成为使用最多的Java EE 企业应用开源框架。
两大核心:以 IOC(Inverse Of Control:控制反转)和 AOP(Aspect Oriented Programming:面向切面编程)为内核。
2.Spring发展历程
- EJB
1997 年,IBM提出了EJB 的思想
1998 年,SUN制定开发标准规范 EJB1.0
1999 年,EJB1.1 发布
2001 年,EJB2.0 发布
2003 年,EJB2.1 发布
2006 年,EJB3.0 发布- Spring
Rod Johnson( Spring 之父)
改变Java世界的大师级人物
2002年编著《Expert one on one J2EE design and development》
指出了JavaEE和EJB组件框架中的存在的一些主要缺陷;提出普通java类依赖注>入更为简单的解决方案。
2004年编著《Expert one-on-one J2EE Development without EJB》
阐述了JavaEE开发时不使用EJB的解决方式(Spring 雏形)
同年4月spring1.0诞生
2006年10月,发布 Spring2.0
2009年12月,发布 Spring3.0
2013年12月,发布 Spring4.0
2017年9月, 发布最新 Spring5.0 通用版(GA)
3.Spring优势
- ①方便解耦,简化开发
Spring就是一个容器,可以将所有对象创建和关系维护交给Spring管理
什么是耦合度?对象之间的关系,通常说当一个模块(对象)更改时也需要更改其他模块(对象),这就是耦合,耦合度过高会使代码的维护成本增加。要尽量解耦 - ②AOP编程的支持
Spring提供面向切面编程,方便实现程序进行权限拦截,运行监控等功能。 - ③声明式事务的支持
通过配置完成事务的管理,无需手动编程 - ④方便测试,降低JavaEE API的使用
Spring对Junit4支持,可以使用注解测试 - ⑤方便集成各种优秀框架
不排除各种优秀的开源框架,内部提供了对各种优秀框架的直接支持
4.Spring体系结构
二、初识IOC
1.概述
**控制反转(Inverse Of Control)**不是什么技术,而是一种设计思想。它的目的是指导我们设计出更加松耦合的程序。
控制:在java中指的是对象的控制权限(创建、销毁)
反转:指的是对象控制权由原来 由开发者在类中手动控制 反转到 由Spring容器控制
比如
- 传统方式
之前我们需要一个userDao实例,需要开发者自己手动创建 new UserDao();- IOC方式
现在我们需要一个userDao实例,直接从spring的IOC容器获得,对象的创建权交给了spring控制
2.自定义IOC容器
①介绍
需求
实现service层与dao层代码解耦合
步骤分析:
a.创建java项目,导入自定义IOC相关坐标
b.编写Dao接口和实现类
c.编写Service接口和实现类
d.编写测试代码
②实现
a.创建java项目,导入自定义IOC相关坐标
<dependencies>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
b.编写Dao接口和实现类
public interface UserDao {
public void save();
}
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("保存成功了...");
}
}
c.编写Service接口和实现类
public interface UserService {
public void save();
}
public class UserServiceImpl implements UserService {
public void save(){
UserDao userDao = new UserDaoImpl();
userDao.save();
}
}
d.编写测试代码
public class UserTest {
@Test
public void testSave() throws Exception {
UserService userService = new UserServiceImpl();
userService.save();
}
}
e.问题
当前service对象和dao对象耦合度太高,而且每次new的都是一个新的对象,导致服务器压力过大。
解耦合的原则是编译期不依赖,而运行期依赖就行了
通过反射修改UserServieceImpl.java
public class UserServiceImpl implements UserService {
public void save() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//调用dao层方法 传统方式:new存在编译器依赖 耦合重
//UserDao userDao = new UserDaoImpl();
//反射
UserDao userDao = (UserDao)Class.forName("com.spring.dao.impl.UserDaoImpl").newInstance();
userDao.save();
}
}
此时又会出现硬编码问题,所以需要配置文件
f.编写beans.xml
把所有需要创建对象的信息定义在配置文件中
<?xml version="1.0" encoding="UTF-8" ?>
<beans>
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl"></bean>
</beans>
g.编写BeanFactory工具类
public class BeanFactory {
private static Map<String,Object> iocmap = new HashMap<>();
//程序启动时,初始化对象实例
static {
//1.读取配置文件
InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");
//2.解析xml(dom4j)
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(resourceAsStream);
//3.编写xpath表达式
String xpath = "//bean";
//4.获取到所有的bean标签
List<Element> list = document.selectNodes(xpath);
//5.遍历并使用反射创建对象实例,存到map集合(ioc容器)中
for (Element element : list) {
String id = element.attributeValue("id");
//className = com.lagou.dao.impl.UserDaoImpl
String className = element.attributeValue("class");
//使用反射生成实例对象
Object o = Class.forName(className).newInstance();
//存到map中 key id:value o
iocmap.put(id,o);
}
} catch (DocumentException | ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
//获取指定id的对象实例
public static Object getBean(String beanId){
Object o = iocmap.get(beanId);
return o;
}
}
h.修改UserServiceImpl实现类
public class UserServiceImpl implements UserService {
public void save() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//调用dao层方法 传统方式:new存在编译器依赖 耦合重
//UserDao userDao = new UserDaoImpl();
//反射
//UserDao userDao = (UserDao)Class.forName("com.spring.dao.impl.UserDaoImpl").newInstance();
UserDao userDao = (UserDao)BeanFactory.getBean("userDao");
userDao.save();
}
}
3.知识小结
- 其实升级后的BeanFactory就是一个简单的Spring的IOC容器所具备的功能。
- 之前我们需要一个userDao实例,需要开发者自己手动创建 new UserDao();
- 现在我们需要一个userdao实例,直接从spring的IOC容器获得,对象的创建权交给了spring控制
- 最终目标:代码解耦合
三 Spring快速入门
1.介绍
需求:借助spring的IOC实现service层与dao层代码解耦合
步骤分析
- 创建java项目,导入spring开发基本坐标
- 编写Dao接口和实现类
- 创建spring核心配置文件
- 在spring配置文件中配置 UserDaoImpl
- 使用spring相关API获得Bean实例
2. 实现
①创建java项目,导入spring开发基本坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
②编写Dao接口和实现类
public interface UserDao {
public void save();
}
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("dao层被调用了...");
}
}
③创建spring核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
④在spring配置文件中配置 UserDaoImpl
<!--在spring配置文件中配置 UserDaoImpl
id 唯一标识
class 类全路径
-->
<bean id="userDao" class="com.lagou.dao.impl.UserDaoImpl"></bean>
⑤使用spring相关API获得Bean实例
@Test
public void test1(){
//1.获取到spring上下文对象 借助上下文对象可以获取到IOC容器中的bean对象
ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.使用上下文对象从IOC容器中获取到Bean对象
IUserDao userDao = (IUserDao)classPathXmlApplicationContext.getBean("userDao");
//3.调用方法
userDao.save();
}
3.知识小结
Spring的开发步骤
- 导入坐标
- 创建Bean
- 创建applicationContext.xml
- 在配置文件中进行Bean配置
- 创建ApplicationContext对象,执行getBean
四、Spring相关API
1.API继承体系介绍
Spring的API体系异常庞大,我们现在只关注两个BeanFactory和ApplicationContext
2.BeanFactory
BeanFactory是 IOC 容器的核心接口,它定义了IOC的基本功能
特点:在第一次调用getBean()方法时,创建指定对象的实例
BeanFactory xmlBeanFactory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
3.ApplicationContext
代表应用上下文对象,可以获得spring中IOC容器的Bean对象
特点:在spring容器启动时,加载并创建所有对象的实例
常用实现类
- ClassPathXmlApplicationContext
它是从类的根路径下加载配置文件 推荐使用这种。- FileSystemXmlApplicationContext
它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置。- AnnotationConfigApplicationContext
当使用注解配置容器对象时,需要使用此类来创建 spring 容器。它用来读取注解。
ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
常用方法
- Object getBean(String name);
根据Bean的id从容器中获得Bean实例,返回是Object,需要强转。- < T > T getBean(Class< T > requiredType);
根据类型从容器中匹配Bean实例,当容器中相同类型的Bean有多个时,则此方法会报错。- < T > T getBean(String name,Class< T > requiredType);
根据Bean的id和类型获得Bean实例,解决容器中相同类型Bean有多个情况。
4.知识小结
ApplicationContext app = new ClasspathXmlApplicationContext("xml文件");
//1.根据beanid在容器中找对应的bean对象
IUserDao userDao = (IUserDao)classPathXmlApplicationContext.getBean("userDao");
//2.根据类型在容器中查询 有可能报错情况:根据当前类型匹配到多个实例
IUserDao userDao = classPathXmlApplicationContext.getBean(IUserDao.class);
五、Spring配置文件
1.Bean标签基本配置
< bean id="" class=""></ bean>
- 用于配置对象交由Spring来创建。
- 基本属性:
id:Bean实例在Spring容器中的唯一标识
class:Bean的全限定名- 默认情况下它调用的是类中的 无参构造函数,如果没有无参构造函数则不能创建成功。
2.Bean标签范围配置
<bean id="" class="" scope=""></bean>
scope属性指对象的作用范围,取值如下:
- 当scope的取值为singleton时
Bean的实例化个数:1个
Bean的实例化时机:当Spring核心文件被加载时,实例化配置的Bean实例
Bean的生命周期:
对象创建:当应用加载,创建容器时,对象就被创建了
对象运行:只要容器在,对象一直活着
对象销毁:当应用卸载,销毁容器时,对象就被销毁了- 当scope的取值为prototype时
Bean的实例化个数:多个
Bean的实例化时机:当调用getBean()方法时实例化Bean
Bean的生命周期:
对象创建:当使用对象时,创建新的对象实例
对象运行:只要对象在使用中,就一直活着
对象销毁:当对象长时间不用时,被 Java 的垃圾回收器回收了
3.Bean生命周期配置
<bean id="" class="" scope="" init-method="" destroy-method=""></bean>
* init-method:指定类中的初始化方法名称
* destroy-method:指定类中销毁方法名称
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl" init-method="init" destroy-method="destory"></bean>
public class UserDaoImpl implements IUserDao {
public void init(){
System.out.println("初始化方法执行了。。。");
}
public void destory(){
System.out.println("销毁方法执行了。。。");
}
public void save() {
System.out.println("DAO被调用了...");
}
}
@Test
public void test2(){
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
IUserDao userDao1 = (IUserDao) applicationContext.getBean("userDao");
IUserDao userDao2 = (IUserDao) applicationContext.getBean("userDao");
System.out.println(userDao1);
System.out.println(userDao2);
//手动销毁
//applicationContext.close();
}
4.Bean实例化三种方式
- 无参构造方法实例化
- 工厂静态方法实例化
- 工厂普通方法实例化
①无参构造方法实例化
它会根据默认无参构造方法来创建类对象,如果bean中没有默认无参构造函数,将会创建失败
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl"/>
②工厂静态方法实例化
应用场景
依赖的jar包中有个A类,A类中有个静态方法m1,m1方法的返回值是一个B对象。如果我们频繁使用B对象,此时我们可以将B对象的创建权交给spring的IOC容器,以后我们在使用B对象时,无需调用A类中的m1方法,直接从IOC容器获得。
public class StaticFactoryBean {
public static IUserDao creatUserDao(){
return new UserDaoImpl();
}
}
<bean id="userDao" class="com.spring.factory.StaticFactoryBean" factory-method="creatUserDao"></bean>
③工厂普通方法实例化
应用场景
依赖的jar包中有个A类,A类中有个普通方法m1,m1方法的返回值是一个B对象。如果我们频繁使用B对象,此时我们可以将B对象的创建权交给spring的IOC容器,以后我们在使用B对象时,无需调用A类中的m1方法,直接从IOC容器获得。
public class DynamicFactoryBean {
public IUserDao creatUserDao(){
return new UserDaoImpl();
}
}
<bean id="dynamicFactoryBean" class="com.spring.factory.DynamicFactoryBean"></bean>
<bean id="userDao" factory-bean="dynamicFactoryBean" factory-method="creatUserDao"></bean>
5.Bean依赖注入概述
依赖注入DI(Dependency Injection):它是Spring框架核心 IOC 的具体实现。
在编写程序时,通过控制反转,把对象的创建交给了 Spring,但是代码中不可能出现没有依赖的情况。IOC 解耦只是降低他们的依赖关系,但不会消除。例如:业务层仍会调用持久层的方法。
那这种业务层和持久层的依赖关系,在使用 Spring 之后,就让 Spring 来维护了。简单的说,就是通过框架把持久层对象传入业务层,而不用我们自己去获取。
6.Bean依赖注入方式
①构造方法
在UserServiceImpl中创建有参构造
public class UserServiceImpl implements IUserService {
private IUserDao userDao;
public UserServiceImpl(IUserDao userDao) {
this.userDao = userDao;
}
@Override
public void save() {
//调用dao层的save方法
userDao.save();
}
}
配置Spring容器调用有参构造时进行注入
<!--配置UserService-->
<bean id="userService" class="com.spring.serveice.impl.UserServiceImpl">
<!-- index="0"表示有参构造的第一个参数-->
<!--<constructor-arg index="0" type="com.spring.dao.IUserDao" ref="userDao"/>-->
<!-- name="userDao"表示有参构造的属性名 ref是指存入容器中的UserDao实例的id -->
<constructor-arg name="userDao" ref="userDao"/>
</bean>
②set方法
在UserServiceImpl中创建set方法
public class UserServiceImpl implements UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void save() {
userDao.save();
}
}
配置Spring容器调用set方法进行注入
<!--配置UserService-->
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.spring.serveice.impl.UserServiceImpl">
<!--set方法依赖注入-->
<property name="userDao" ref="userDao"></property>
</bean>
③P命名空间注入
P命名空间注入本质也是set方法注入,但比起上述的set方法注入更加方便,主要体现在配置文件中,如下:
引入P命名空间:
xmlns:p="http://www.springframework.org/schema/p"
修改注入方式:
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl"/>
<bean id="userService" class="com.spring.service.impl.UserServiceImpl" p:userDao-ref="userDao"/>
7.Bean依赖注入的数据类型
上面操作,都是注入Bean对象,除了对象的引用可以注入,普通数据类型和集合都可以在容器中进行注入。
注入数据的三种数据类型
- 普通数据类型
- 引用数据类型
- 集合数据类型
其中引用数据类型,此处就不再赘述了,之前的操作都是对UserDao对象的引用进行注入的。下面将以set方法注入为例,演示普通数据类型和集合数据类型的注入。
①注入普通数据类型
public class UserDaoImpl implements IUserDao {
private String username;
private Integer age;
public void setUsername(String username) {
this.username = username;
}
public void setAge(Integer age) {
this.age = age;
}
public void save() {
System.out.println(username);
System.out.println(age);
System.out.println("DAO被调用了...");
}
}
<bean id="user" class="com.lagou.domain.User">
<property name="username" value="tom"/>
<property name="age" value="18"/>
</bean>
②注入集合数据类型
a.List集合注入
public class UserDaoImpl implements UserDao {
private List<Object> list;
public void save() {
System.out.println(list);
System.out.println("保存成功了...");
}
}
<bean id="user" class="com.spring.domain.User">
<property name="username" value="jack"/>
<property name="age" value="18"/>
</bean>
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl">
<property name="list">
<list>
<value>aaa</value>
<ref bean="user"></ref>
</list>
</property>
</bean>
b.Set集合注入
public class UserDaoImpl implements UserDao {
private Set<Object> set;
public void setSet(Set<Object> set) {
this.set = set;
}
public void save() {
System.out.println(set);
System.out.println("保存成功了...");
}
}
<bean id="user" class="com.spring.domain.User">
<property name="username" value="jack"/>
<property name="age" value="18"/>
</bean>
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl">
<property name="set">
<list>
<value>bbb</value>
<ref bean="user"></ref>
</list>
</property>
</bean>
c.Array数组注入
public class UserDaoImpl implements UserDao {
private Object[] array;
public void setArray(Object[] array) {
this.array = array;
}
public void save() {
System.out.println(Arrays.toString(array));
System.out.println("保存成功了...");
}
}
<bean id="user" class="com.spring.domain.User">
<property name="username" value="jack"/>
<property name="age" value="18"/>
</bean>
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl">
<property name="array">
<array>
<value>ccc</value>
<ref bean="user"></ref>
</array>
</property>
</bean>
d.Map集合注入
public class UserDaoImpl implements UserDao {
private Map<String, Object> map;
public void setMap(Map<String, Object> map) {
this.map = map;
}
public void save() {
System.out.println(map);
System.out.println("保存成功了...");
}
}
<bean id="user" class="com.spring.domain.User">
<property name="username" value="jack"/>
<property name="age" value="18"/>
</bean>
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl">
<property name="map">
<map>
<entry key="k1" value="ddd"/>
<entry key="k2" value-ref="user"></entry>
</map>
</property>
</bean>
e.Properties配置注入
public class UserDaoImpl implements UserDao {
private Properties properties;
public void setProperties(Properties properties) {
this.properties = properties;
}
public void save() {
System.out.println(properties);
System.out.println("保存成功了...");
}
}
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl">
<property name="properties">
<props>
<prop key="k1">v1</prop>
<prop key="k2">v2</prop>
<prop key="k3">v3</prop>
</props>
</property>
</bean>
8.配置文件模块化
实际开发中,Spring的配置内容非常多,这就导致Spring配置很繁杂且体积很大,所以,可以将部分配置拆解到其他配置文件中,也就是所谓的配置文件模块化。
①并列的多个配置文件
ApplicationContext act = new ClassPathXmlApplicationContext("beans1.xml","beans2.xml","...");
②主从配置文件
<import resource="applicationContext-xxx.xml"/>
注意:
同一个xml中不能出现相同名称的bean,如果出现会报错
多个xml如果出现相同名称的bean,不会报错,但是后加载的会覆盖前加载的bean
9.知识小结
Spring的重点配置
< bean>标签:创建对象并放到spring的IOC容器
id属性:在容器中Bean实例的唯一标识,不允许重复
class属性:要实例化的Bean的全限定名
scope属性:Bean的作用范围,常用是Singleton(默认)和prototype
< constructor-arg>标签:属性注入
name属性:属性名称
value属性:注入的普通属性值
ref属性:注入的对象引用值
< property>标签:属性注入
name属性:属性名称
value属性:注入的普通属性值
ref属性:注入的对象引用值
< list>
< set>
< array>
< map>
< props>
< import>标签:导入其他的Spring的分文件
六、DbUtils(IOC实战)
1.DbUtils是什么
DbUtils是Apache的一款用于简化Dao代码的工具类,它底层封装了JDBC技术。
核心对象
QueryRunner queryRunner = new QueryRunner(DataSource dataSource);
核心方法
int update(); 执行增、删、改语句
T query(); 执行查询语句
ResultSetHandler< T> 这是一个接口,主要作用是将数据库返回的记录封装到实体对象
比如
查询数据库所有账户信息到Account实体中
public class DbUtilsTest {
@Test
public void findAllTest() throws Exception {
// 创建DBUtils工具类,传入连接池
QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource());
// 编写sql
String sql = "select * from account";
// 执行sql
List<Account> list = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));
// 打印结果
for (Account account : list) {
System.out.println(account);
}
}
}
2.Spring的xml整合DbUtils
①介绍
需求
基于Spring的xml配置实现账户的CRUD案例
步骤分析
- 准备数据库环境
- 创建java项目,导入坐标
- 编写Account实体类
- 编写AccountDao接口和实现类
- 编写AccountService接口和实现类
- 编写spring核心配置文件
- 编写测试代码
②实现
a.准备数据库环境
CREATE DATABASE `spring_db`;
USE `spring_db`;
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) DEFAULT NULL,
`money` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ;
insert into `account`(`id`,`name`,`money`) values (1,'tom',1000), (2,'jerry',1000);
b.创建java项目,导入坐标
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
c.编写Account实体类
public class Account {
private Integer id;
private String name;
private Double money;
get/set方法
toString方法
}
d.编写AccountDao接口和实现类
public interface AccountDao {
public List<Account> findAll();
public Account findById(Integer id);
public void save(Account account);
public void update(Account account);
public void delete(Integer id);
}
public class AccountImpl implements AccountDao {
private QueryRunner queryRunner;
public void setQueryRunner(QueryRunner queryRunner) {
this.queryRunner = queryRunner;
}
public List<Account> findAll(){
List<Account> list = null;
String sql = "select * from account";
try {
list = queryRunner.query(sql, new BeanListHandler<Account>(Account.class));
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
public Account findById(Integer id) {
Account account = null;
String sql = "select * from account where id = ?";
try {
account = queryRunner.query(sql, new BeanHandler<Account>(Account.class),id);
} catch (SQLException e) {
e.printStackTrace();
}
return account;
}
public void save(Account account) {
String sql = "insert into account values(null,?,?)";
try {
queryRunner.update(sql, account.getName(), account.getMoney());
} catch (SQLException e) {
e.printStackTrace();
}
}
public void update(Account account) {
String sql = "update account set name = ?,money = ? where id = ?";
try {
queryRunner.update(sql, account.getName(), account.getMoney(),account.getId());
} catch (SQLException e) {
e.printStackTrace();
}
}
public void delete(Integer id) {
String sql = "delete from account where id = ?";
try {
queryRunner.update(sql, id);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
e.编写AccountService接口和实现类
public interface AccountService {
public List<Account> findAll();
public Account findById(Integer id);
public void save(Account account);
public void update(Account account);
public void delete(Integer id);
}
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAll() {
return accountDao.findAll();
}
public Account findById(Integer id) {
return accountDao.findById(id);
}
public void save(Account account) {
accountDao.save(account);
}
public void update(Account account) {
accountDao.update(account);
}
public void delete(Integer id) {
accountDao.delete(id);
}
}
f.编写spring核心配置文件
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--DataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_db"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--QueryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
<!--AccountDao-->
<bean id="accountDao" class="com.spring.dao.impl.AccountImpl">
<property name="queryRunner" ref="queryRunner"/>
</bean>
<!--AccountService-->
<bean id="accountService" class="com.spring.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
</beans>
g.编写测试代码
public class AccountTest {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = (AccountService) classPathXmlApplicationContext.getBean("accountService");
//测试添加
@Test
public void testSave(){
Account account = new Account();
account.setName("lucy");
account.setMoney(888d);
accountService.save(account);
}
//测试查询1
@Test
public void testFindAll(){
List<Account> list = accountService.findAll();
for (Account account : list) {
System.out.println(account);
}
}
//测试查询2
@Test
public void testFindById(){
Account account = accountService.findById(3);
System.out.println(account);
}
//测试修改
@Test
public void testUpdate(){
Account account = new Account();
account.setName("nancy");
account.setMoney(999d);
account.setId(3);
accountService.update(account);
}
//测试删除
@Test
public void testDelete(){
accountService.delete(3);
}
}
h.抽取jdbc配置文件
applicationContext.xml加载jdbc.properties配置文件获得连接信息。
首先,需要引入context命名空间和约束路径:
- 命名空间:
xmlns:context=“http://www.springframework.org/schema/context”- 约束路径:
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
3.知识小结
* DataSource的创建权交由Spring容器去完成
* QueryRunner的创建权交由Spring容器去完成,使用构造方法传递DataSource
* Spring容器加载properties文件
<context:property-placeholder location="xx.properties"/>
<property name="" value="${key}"/>
七、Spring注解开发
Spring是轻代码而重配置的框架,配置比较繁重,影响开发效率,所以注解开发是一种趋势,注解代替xml配置文件可以简化配置,提高开发效率。
1.Spring常用注解
①介绍
Spring常用注解主要是替代 < bean> 的配置
注意
JDK11以后完全移除了javax扩展导致不能使用@resource注解
需要maven引入依赖
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
注意
使用注解进行开发时,需要在applicationContext.xml中配置组件扫描,作用是指定哪个包及其子包下的Bean需要进行扫描以便识别使用注解配置的类、字段和方法。
<!--注解的组件扫描-->
<context:component-scan base-package="com.srping"></context:component-scan>
②实现
a.Bean实例化(IOC)
<bean id="userDao" class="com.spring.dao.impl.UserDaoImpl"></bean>
使用@Compont或@Repository标识UserDaoImpl需要Spring进行实例化
// @Component(value = "userDao")
@Repository // 如果没有写value属性值,Bean的id为:类名首字母小写
public class UserDaoImpl implements UserDao {
}
b.属性依赖注入(DI)
<bean id="userService" class="com.spring.service.impl.UserServiceImpl">
<property name="userDao" ref="userDaoImpl"/>
</bean>
使用@Autowired或者@Autowired+@Qulifier或者@Resource进行userDao的注入
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
// <property name="userDao" ref="userDaoImpl"/>
// @Autowired
// @Qualifier("userDao")
// @Resource(name = "userDaoImpl")
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
c.@Value
使用@Value进行字符串的注入,结合SPEL表达式获得配置参数
@Service
public class UserServiceImpl implements UserService {
@Value("注入普通数据")
private String str;
@Value("${jdbc.driver}")
private String driver;
}
d.@Scope
<bean scope=""/>
使用@Scope标注Bean的范围
@Service
@Scope("singleton")
public class UserServiceImpl implements UserService {{
}
e.Bean生命周期
<bean init-method="init" destroy-method="destory" />
使用@PostConstruct标注初始化方法,使用@PreDestroy标注销毁方法
@PostConstruct
public void init(){
System.out.println("初始化方法....");
}
@PreDestroy
public void destroy(){
System.out.println("销毁方法.....");
}
2.Spring常用注解整合DbUtils
步骤分析
- 拷贝xml配置项目,改为注解配置项目
- 修改AccountDaoImpl实现类
- 修改AccountServiceImpl实现类
- 修改spring核心配置文件
- 编写测试代码
①拷贝xml配置项目,改为常用注解配置项目
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
②修改AccountDaoImpl实现类
@Repository
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner queryRunner;
....
}
③修改AccountServiceImpl实现类
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
....
}
④修改spring核心配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w1.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">
<!--注解的组件扫描-->
<context:component-scan base-package="com.spring"></context:component-scan>
<!--加载jdbc配置文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--把数据库连接池交给IOC容器-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--把QueryRunner交给IOC容器-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"></constructor-arg>
</bean>
</beans>
⑤编写测试代码
public class AccountServiceTest {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = applicationContext.getBean(AccountService.class);
//测试查询
@Test
public void findByIdTest() {
Account account = accountService.findById(3);
System.out.println(account);
}
}
3.Spring新注解
使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
- 非自定义的Bean的配置:< bean>
- 加载properties文件的配置:< context:property-placeholder>
- 组件扫描的配置:< context:component-scan>
- 引入其他文件:< import>
4.Spring纯注解整合DbUtils
步骤分析
- 编写Spring核心配置类
- 编写数据库配置信息类
- 编写测试代码
①编写Spring核心配置类
@Configuration
@ComponentScan("com.spring")
@Import(DataSourceConfig.class)
public class SpringConfig {
@Bean("queryRunner")
public QueryRunner getQueryRunner(@Autowired DataSource dataSource) {
return new QueryRunner(dataSource);
}
}
②编写数据库配置信息类
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfig {
@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")
public DataSource getDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
③编写测试代码
public class AccountServiceTest {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
AccountService accountService = applicationContext.getBean(AccountService.class);
//测试查询
@Test
public void testFindById() {
Account account = accountService.findById(3);
System.out.println(account);
}
}
八、Spring整合Junit
1.普通Junit测试问题
在普通的测试类中,需要开发者手动加载配置文件并创建Spring容器,然后通过Spring相关API获得
Bean实例;如果不这么做,那么无法从容器中获得对象。
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = applicationContext.getBean(AccountService.class);
我们可以让SpringJunit负责创建Spring容器来简化这个操作,开发者可以直接在测试类注入Bean实
例;但是需要将配置文件的名称告诉它。
2.Spring整合Junit
步骤分析
- 导入spring集成Junit的坐标
- 使用@Runwith注解替换原来的运行器
- 使用@ContextConfiguration指定配置文件或配置类
- 使用@Autowired注入需要测试的对象
- 创建测试方法进行测试
①导入spring集成Junit的坐标
<!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
②使用@Runwith注解替换原来的运行器
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {
}
③使用@ContextConfiguration指定配置文件或配置类
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(value = {"classpath:applicationContext.xml"}) 加载spring核心配置文件
@ContextConfiguration(classes = {SpringConfig.class}) // 加载spring核心配置类
public class SpringJunitTest {
}
④使用@Autowired注入需要测试的对象
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class})
public class SpringJunitTest {
@Autowired
private AccountService accountService;
}
⑤创建测试方法进行测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfig.class})
public class SpringJunitTest {
@Autowired
private AccountService accountService;
//测试查询
@Test
public void testFindById() {
Account account = accountService.findById(3);
System.out.println(account);
}
}
AOP
九、转账案例
需求
使用spring框架整合DBUtils技术,实现用户转账功能
1.基础功能
步骤分析
- 创建java项目,导入坐标
- 编写Account实体类
- 编写AccountDao接口和实现类
- 编写AccountService接口和实现类
- 编写spring核心配置文件
- 编写测试代码
①创建java项目,导入坐标
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
②编写Account实体类
public class Account {
private Integer id;
private String name;
private Double money;
get/set方法
toString方法
}
③编写AccountDao接口和实现类
public interface AccountDao {
//转出
public void out(String outUser,Double money);
//转入
public void in(String inUser,Double money);
}
@Repository("accountDao") //生成该类实例存到IOC容器中
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner queryRunner;
public void out(String outUser, Double money) {
String sql = "update account set money=money-? where name=?";
try {
queryRunner.update(sql,money,outUser);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void in(String inUser, Double money) {
String sql = "update account set money=money+? where name=?";
try {
queryRunner.update(sql,money,inUser);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
④编写AccountService接口和实现类
public interface AccountService {
//转账
public void transfer(String outUser,String inUser,Double money);
}
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
//转账方法
public void transfer(String outUser, String inUser, Double money) {
//减钱
accountDao.out(outUser, money);
//int i = 1/0;
//加钱
accountDao.in(inUser, money);
}
}
⑤编写spring核心配置文件
<?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">
<!--开启注解扫描-->
<context:component-scan base-package="com.lagou"></context:component-scan>
<!--引入properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--配置DataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置QueryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
</beans>
⑥编写测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class AccountTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer(){
accountService.transfer("tom","jerry",100d);
}
}
⑦问题分析
上面的代码事务在dao层,转出转入操作都是一个独立的事务,但实际开发,应该把业务逻辑控制在
一个事务中,所以应该将事务挪到service层。
2.传统事务
步骤分析
- 编写线程绑定工具类
- 编写事务管理器
- 修改service层代码
- 修改dao层代码
①编写线程绑定工具类
//连接工具类:从数据源中获取一个连接 并且将获取到的连接与线程进项绑定
@Component
public class ConnectionUtils {
@Autowired
private DataSource dataSource;
//ThreadLocal:线程内容部的存储类 可以在指定的线程内存储数据
private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
//获取当前线程绑定的连接 如果获取的连接为空,那么就要从数据源中获取连接 并放到ThreadLocal中(绑定到当前线程)
public Connection getConnection(){
//1.先从ThreadLocal中获取连接
Connection connection = threadLocal.get();
//2.判断当前线程中是否有Connection
if (connection == null){
//3.从数据源中获取一个连接并存入ThreadLocal中
try {
connection = dataSource.getConnection();
threadLocal.set(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
//解除当前线程的绑定
public void removeThreadLocal(){
threadLocal.remove();
}
}
②编写事务管理器
//事务管理器工具类 包含:开启事务 提交事务 回滚事务 释放资源
@Component
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
//开启事务
public void beginTransaction(){
//获取connection对象
Connection connection = connectionUtils.getThreadConnection();
try {
//开启一个手动事务
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
//提交事务
public void commit(){
Connection connection = connectionUtils.getThreadConnection();
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
//回滚事务
public void rollback(){
Connection connection = connectionUtils.getThreadConnection();
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
//释放资源
public void release(){
Connection connection = connectionUtils.getThreadConnection();
try {
//将手动事务改为自动提交事务
connection.setAutoCommit(true);
//将连接归还到连接池
connectionUtils.getThreadConnection().close();
//解除线程绑定
connectionUtils.removeThreadLocal();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
③修改service层代码
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Autowired
private TransactionManager transactionManager;
//转账方法
public void transfer(String outUser, String inUser, Double money) {
//手动开启事务 调用事务管理器中的开启事务方法
transactionManager.beginTransaction();
try {
//减钱
accountDao.out(outUser, money);
//int i = 1/0;
//加钱
accountDao.in(inUser, money);
//手动提交事务
transactionManager.commit();
} catch (Exception e) {
e.printStackTrace();
//手动回滚事务
transactionManager.rollback();
}finally {
//手动释放资源
transactionManager.release();
}
}
}
④修改dao层代码
@Repository("accountDao") //生成该类实例存到IOC容器中
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner queryRunner;
@Autowired
private ConnectionUtils connectionUtils;
public void out(String outUser, Double money) {
String sql = "update account set money=money-? where name=?";
try {
queryRunner.update(connectionUtils.getThreadConnection(),sql,money,outUser);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void in(String inUser, Double money) {
String sql = "update account set money=money+? where name=?";
try {
queryRunner.update(connectionUtils.getThreadConnection(),sql,money,inUser);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
⑤问题分析
上面代码,通过对业务层改造,已经可以实现事务控制了,但是由于我们添加了事务控制,也产生了一个新的问题: 业务层方法变得臃肿了,里面充斥着很多重复代码。并且业务层方法和事务控制方法耦合了,违背了面向对象的开发思想。
十、Proxy优化转账案例
我们可以将业务代码和事务代码进行拆分,通过动态代理的方式,对业务方法进行事务的增强。这样就不会对业务层产生影响,解决了耦合性的问题
常用的动态代理技术
- JDK 代理 : 基于接口的动态代理技术·:利用拦截器(必须实现invocationHandler)加上反射机制生成一个代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理,从而实现方法增强
- CGLIB代理:基于父类的动态代理技术:动态生成一个要代理的子类,子类重写要代理的类的所有不是final的方法。在子类中采用方法拦截技术拦截所有的父类方法的调用,顺势织入横切逻辑,对方法进行增强
1.JDK动态代理方式
JDK工厂类
//JDK动态代理工厂类
@Component
public class JDKProxyFactory {
@Autowired
private AccountService accountService;
@Autowired
private TransactionManager transactionManager;
//采用JDK动态代理生成目标类的代理对象
public AccountService createAccountServiceJDKProxy() {
/*
newProxyInstance()的三个参数
ClassLoader loader :类加载器 借助被调用对象获取到类加载器
Class<?>[] interfaces :被代理类所需实现的全部接口
InvocationHandler h :当代理对象调用接口中的任意方法时 那么都会执行InvocationHandler中的invoke方法
*/
AccountService accountServiceProxy = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
@Override
//proxy:当前代理对象引用 method:被调用的目标方法引用 args:被调用的目标方法所用到的参数
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
try {
//System.out.println("目标方法执行前动态进行了方法增强");
//手动开启事务 调用事务管理器中的开启事务方法
transactionManager.beginTransaction();
//让被代理对象的原方法执行
result = method.invoke(accountService, args);
//System.out.println("目标方法执行后动态进行了方法增强");
//手动提交事务
transactionManager.commit();
} catch (Exception e) {
e.printStackTrace();
//手动回滚事务
transactionManager.rollback();
}finally {
//手动释放资源
transactionManager.release();
}
return result;
}
});
return accountServiceProxy;
}
}
测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountTest {
@Autowired
private JDKProxyFactory jdkProxyFactory;
@Test
public void testTransferProxyJDK() throws Exception {
//当前返回的实际是AccountService的代理对象proxy
AccountService accountServiceJDKProxy = jdkProxyFactory.createAccountServiceJDKProxy();
//代理对象proxy调用接口中的任意方法时都会执行底层的invoke方法
accountServiceJDKProxy.transfer("tom", "jerry", 100d);
}
}
2.CGLIB动态代理方式
Cglib工厂类
//采用cglib动态代理来对目标类进行方法的动态增强(添加事务控制)
@Component
public class CglibProxyFactory {
@Autowired
private AccountService accountService;
@Autowired
private TransactionManager transactionManager;
public AccountService createAccountServiceCglibProxy(){
//编写cglib对应的API来生成代理对象进行返回
//参数1:目标类的字节码对象 参数2:动作类 当代理对象调用目标对象中的原方法时会执行intercept方法
AccountService accountServiceProxy = (AccountService) Enhancer.create(accountService.getClass(), new MethodInterceptor() {
@Override
/*
Object o :代表生成的代理对象
Method method :调用目标方法的引用
Object[] objects :方法入参
MethodProxy methodProxy :代理方法
*/
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
Object result = null;
try {
//手动开启事务 调用事务管理器中的开启事务方法
transactionManager.beginTransaction();
//原方法调用
result = method.invoke(accountService, objects);
//手动提交事务
transactionManager.commit();
} catch (Exception e) {
e.printStackTrace();
//手动回滚事务
transactionManager.rollback();
} finally {
//手动释放资源
transactionManager.release();
}
return result;
}
});
return accountServiceProxy;
}
}
测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceTest {
@Autowired
private CglibProxyFactory cglibProxyFactory;
@Test
public void testTransferProxyCiglib() throws Exception {
AccountService accountServiceCglibProxy = cglibProxyFactory.createAccountServiceCglibProxy();
//代理对象proxy调用接口中的任意方法时都会执行底层的invoke方法
accountServiceCglibProxy.transfer("tom", "jerry", 100d);
}
}
十一、初识AOP
1.什么是AOP
AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程
AOP 是 OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
这样做的好处是:
- 在程序运行期间,在不修改源码的情况下对方法进行功能增强
- 逻辑清晰,开发核心业务的时候,不必关注增强业务的代码
- 减少重复代码,提高开发效率,便于后期维护
2.AOP底层实现
实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从
而完成功能的增强。
3.AOP相关术语
Spring 的 AOP 实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的
部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
在正式讲解 AOP 的操作之前,我们必须理解 AOP 的相关术语,常用的术语如下:
- Target(目标对象):代理的目标对象
- Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类
- Joinpoint(连接点):所谓连接点是指那些可以被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点
- Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义
- Advice(通知/ 增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知
分类:前置通知、后置通知、异常通知、最终通知、环绕通知- Aspect(切面):是切入点和通知(引介)的结合
- Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织
入,而AspectJ采用编译期织入和类装载期织入
4.AOP开发明确事项
①开发阶段(我们做的)
- 编写核心业务代码(目标类的目标方法) 切入点
- 把公用代码抽取出来,制作成通知(增强功能方法) 通知
- 在配置文件中,声明切入点与通知间的关系,即切面
②运行阶段(Spring框架完成的)
Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对
象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑
运行。
③底层代理实现
在 Spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
- 当bean实现接口时,会用JDK代理模式
- 当bean没有实现接口,用cglib实现( 可以强制使用cglib(在spring配置中加入
<aop:aspectjautoproxy proxyt-target-class=”true”/>)
5.知识小结
- aop:面向切面编程
- aop底层实现:基于JDK的动态代理 和 基于Cglib的动态代理
- aop的重点概念:
Pointcut(切入点):真正被增强的方法
Advice(通知/ 增强):封装增强业务逻辑的方法
Aspect(切面):切点+通知
Weaving(织入):将切点与通知结合,产生代理对象的过程
十二、基于XML的AOP开发
1.快速入门
步骤分析
- 创建java项目,导入AOP相关坐标
- 创建目标接口和目标实现类(定义切入点)
- 创建通知类及方法(定义通知)
- 将目标类和通知类对象创建权交给spring
- 在核心配置文件中配置织入关系,及切面
- 编写测试代码
①创建java项目,导入AOP相关坐标
<dependencies>
<!--导入spring的context坐标,context依赖aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- aspectj的织入(切点表达式需要用到该jar包) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!--spring整合junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
②创建目标接口和目标实现类
public interface AccountService {
public void transfer();
}
public class AccountServiceImpl implements AccountService {
@Override
public void transfer() {
System.out.println("转账业务...");
}
}
③创建通知类
public class MyAdvice {
public void before() {
System.out.println("前置通知...");
}
}
④将目标类和通知类对象创建权交给spring
<!--目标类交给IOC容器-->
<bean id="accountService" class="com.spring.service.impl.AccountServiceImpl"></bean>
<!--通知类交给IOC容器-->
<bean id="myAdvice" class="com.spring.advice.MyAdvice"></bean>
⑤在核心配置文件中配置织入关系及切面
导入aop命名空间
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--目标类交给IOC容器-->
<bean id="accountService" class="com.spring.service.impl.AccountServiceImpl"></bean>
<!--通知类交给IOC容器-->
<bean id="myAdvice" class="com.spring.advice.MyAdvice"></bean>
<!--AOP配置-->
<aop:config>
<!--配置切面:切入点+通知-->
<aop:aspect ref="myAdvice">
<aop:before method="before" pointcut="execution(public void com.spring.service.impl.AccountServiceImpl.transfer())"/>
</aop:aspect>
</aop:config>
</beans>
⑥编写测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class AccountServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer(){
accountService.transfer();
}
}
2.XML配置AOP详解
①切点表达式
表达式语法:
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
● 访问修饰符可以省略
● 返回值类型、包名、类名、方法名可以使用星号 * 代替,代表任意
● 包名与类名之间一个点 . 代表当前包下的类,两个点 … 表示当前包及其子包下的类
● 参数列表可以使用两个点 … 表示任意个数,任意类型的参数列表
例如
execution(public void com.spring.service.impl.AccountServiceImpl.transfer(java.lang.String))
execution(void com.pring.service.impl.AccountServiceImpl.transfer())
execution(* *.*.*.*.*.*())
execution(* *..*.*())
execution(* *..*.*(..))
切点表达式抽取
当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用 pointcut-ref 属性代替
pointcut 属性来引用抽取后的切点表达式。
<!--AOP配置-->
<aop:config>
<!--抽取切点表达式-->
<aop:pointcut id="myPointcut" expression="execution(* com.spring.service.impl.AccountServiceImpl.*(..))"/>
<!--配置切面:切入点+通知-->
<aop:aspect ref="myAdvice">
<!--<aop:before method="before" pointcut="execution(public void com.spring.service.impl.AccountServiceImpl.transfer())"/>-->
<!--<aop:after-returning method="afterReturning" pointcut="execution(public void com.spring.service.impl.AccountServiceImpl.transfer())"/>-->
<aop:before method="before" pointcut-ref="myPointcut"/>
<aop:after-returning method="afterReturning" pointcut-ref="myPointcut"/>
</aop:aspect>
</aop:config>
②通知类型
通知的配置语法:
<aop:通知类型 method=“通知类中方法名” pointcut=“切点表达式"></aop:通知类型>
注意:通常情况下,环绕通知都是独立使用的
3. 知识小结
* aop织入的配置
<aop:config>
<aop:aspect ref=“通知类”>
<aop:before method=“通知方法名称” pointcut=“切点表达式"></aop:before>
</aop:aspect>
</aop:config>
* 通知的类型
前置通知、后置通知、异常通知、最终通知
环绕通知
* 切点表达式
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
十三、 基于注解的AOP开发
1.快速入门
步骤分析
- 创建java项目,导入AOP相关坐标
- 创建目标接口和目标实现类(定义切入点)
- 创建通知类(定义通知)
- 将目标类和通知类对象创建权交给spring
- 在通知类中使用注解配置织入关系,升级为切面类
- 在配置文件中开启组件扫描和 AOP 的自动代理
- 编写测试代码
①创建java项目,导入AOP相关坐标
<dependencies>
<!--导入spring的context坐标,context依赖aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- aspectj的织入 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!--spring整合junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
②创建目标接口和目标实现类
public interface AccountService {
public void transfer();
}
@Service
public class AccountServiceImpl implements AccountService
public void transfer() {
System.out.println("转账方法执行了...");
}
}
③创建通知类
@Component
@Aspect //升级为切面类:配置切入点和通知的关系
public class MyAdvice {
@Before("execution(* com.spring.service.impl.AccountServiceImpl.*(..))")
public void before(){
System.out.println("前置通知执行了...");
}
}
④将目标类和通知类对象创建权交给spring
@Service
public class AccountServiceImpl implements AccountService {}
@Component
public class MyAdvice {}
⑤ 在通知类中使用注解配置织入关系,升级为切面类
//通知类
@Component
@Aspect //升级为切面类:配置切入点和通知的关系
public class MyAdvice {
@Before("execution(* com.spring.service.impl.AccountServiceImpl.*(..))")
public void before(){
System.out.println("前置通知执行了...");
}
}
⑥在配置文件中开启组件扫描和 AOP 的自动代理
<?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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.lagou"></context:component-scan>
<!-- AOP的自动代理 spring会采用动态代理完成植入增强,并且生成代理
proxy-target-class="true"表示强制使用cglib动态代理
-->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
⑦编写测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AccountServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer(){
accountService.transfer();
}
}
2.注解配置AOP详解
①切点表达式
切点表达式的抽取
@Component
@Aspect //升级为切面类:配置切入点和通知的关系
public class MyAdvice {
@Pointcut("execution(* com.spring.service.impl.AccountServiceImpl.*(..))")
public void myPoint(){
}
@Before("MyAdvice.myPoint()")
public void before(){
System.out.println("前置通知执行了...");
}
@AfterReturning("MyAdvice.myPoint()")
public void afterReturning(){
System.out.println("后置通知执行了...");
}
}
② 通知类型
通知的配置语法:@通知注解(“切点表达式")
注意:
当前四个通知组合在一起时,执行顺序如下:
@Before -> @After -> @AfterReturning(如果有异常:@AfterThrowing)
@Component
@Aspect //升级为切面类:配置切入点和通知的关系
public class MyAdvice {
@Pointcut("execution(* com.lagou.service.impl.AccountServiceImpl.*(..))")
public void myPoint(){
}
@Before("MyAdvice.myPoint()")
public void before(){
System.out.println("前置通知执行了...");
}
@AfterReturning("MyAdvice.myPoint()")
public void afterReturning(){
System.out.println("后置通知执行了...");
}
@After("MyAdvice.myPoint()")
public void after(){
System.out.println("最终通知执行了...");
}
@AfterThrowing("MyAdvice.myPoint()")
public void afterThrowing(){
System.out.println("异常通知执行了...");
}
@Around("MyAdvice.myPoint()")
public Object arround(ProceedingJoinPoint pjp){
Object proceed = null;
try {
System.out.println("前置通知执行了...");
proceed = pjp.proceed();
System.out.println("后置通知执行了...");
} catch (Throwable throwable) {
throwable.printStackTrace();
System.out.println("异常通知执行了...");
}finally {
System.out.println("最终通知执行了...");
}
return proceed;
}
}
先最终通知后后置通知,可以理解为spring注解的一个bug,或者可以使用环绕通知来手动配置通知执行顺序,平时还是建议使用xml配置通知增强
③纯注解配置
@Configuration //变成核心配置类
@ComponentScan("com.spring") //开启注解扫描
@EnableAspectJAutoProxy //开启了AOP的自动代理 替代了<aop:aspectj-autoproxy>
public class SpringConfig {
}
3.知识小结
* 使用@Aspect注解,标注切面类
* 使用@Before等注解,标注通知方法
* 使用@Pointcut注解,抽取切点表达式
* 配置aop自动代理 <aop:aspectj-autoproxy/> 或 @EnableAspectJAutoProxy
十四、AOP优化转账案例
依然使用前面的转账案例,将两个代理工厂对象直接删除!改为spring的aop思想来实现
1.xml配置实现
①配置文件
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.spring"></context:component-scan>
<!--引入properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--配置DataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置QueryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
<!--AOP配置-->
<aop:config>
<!--1.切点表达式-->
<aop:pointcut id="myPoint" expression="execution(* com.spring.service.impl.AccountServiceImpl.*(..))"/>
<!--2.切面配置-->
<aop:aspect ref="transactionManager">
<aop:before method="beginTransaction" pointcut-ref="myPoint"/>
<aop:after-returning method="commit" pointcut-ref="myPoint"/>
<aop:after-throwing method="rollback" pointcut-ref="myPoint"/>
<aop:after method="release" pointcut-ref="myPoint"/>
</aop:aspect>
</aop:config>
</beans>
②事务管理器(通知)
@Component("transactionManager")
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
//开启事务
public void beginTransaction(){
//获取connection对象
Connection connection = connectionUtils.getThreadConnection();
try {
//开启一个手动事务
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
//提交事务
public void commit(){
Connection connection = connectionUtils.getThreadConnection();
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
//回滚事务
public void rollback(){
Connection connection = connectionUtils.getThreadConnection();
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
//释放资源
public void release(){
Connection connection = connectionUtils.getThreadConnection();
try {
//将手动事务改为自动提交事务
connection.setAutoCommit(true);
//将连接归还到连接池
connectionUtils.getThreadConnection().close();
//解除线程绑定
connectionUtils.removeThreadLocal();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.注解配置实现
①配置文件
<?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"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.lagou"></context:component-scan>
<!--引入properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--开启AOP自动代理-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!--配置DataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置QueryRunner-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
</beans>
②事务管理器(通知)
@Component("transactionManager")
@Aspect //变成切面类
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
@Around("execution(* com.spring.service.impl.AccountServiceImpl.*(..))")
public Object around(ProceedingJoinPoint pjp) throws SQLException {
Object proceed = null;
try {
//将自动事务改为手动事务
connectionUtils.getThreadConnection().setAutoCommit(false);
proceed = pjp.proceed();
//手动提交事务
connectionUtils.getThreadConnection().commit();
} catch (Throwable throwable) {
throwable.printStackTrace();
//手动回滚事务
connectionUtils.getThreadConnection().rollback();
}finally {
//将手动事务恢复成自动事务
connectionUtils.getThreadConnection().setAutoCommit(true);
//将连接归还到连接池
connectionUtils.getThreadConnection().close();
//解除线程绑定
connectionUtils.removeThreadLocal();
}
return proceed;
}
//开启事务
public void beginTransaction(){
//获取connection对象
Connection connection = connectionUtils.getThreadConnection();
try {
//开启一个手动事务
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
//提交事务
public void commit(){
Connection connection = connectionUtils.getThreadConnection();
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
//回滚事务
public void rollback(){
Connection connection = connectionUtils.getThreadConnection();
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
//释放资源
public void release(){
Connection connection = connectionUtils.getThreadConnection();
try {
//将手动事务改为自动提交事务
connection.setAutoCommit(true);
//将连接归还到连接池
connectionUtils.getThreadConnection().close();
//解除线程绑定
connectionUtils.removeThreadLocal();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Spring JDBCTemplate & 声明式事务
十五、Spring的JdbcTemplate
1.JdbcTemplate是什么?
JdbcTemplate是spring框架中提供的一个模板对象,是对原始繁琐的Jdbc API对象的简单封装。
核心对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSource dataSource);
核心方法
int update(); 执行增、删、改语句
List<T> query(); 查询多个
T queryForObject(); 查询一个
new BeanPropertyRowMapper<>(); 实现ORM映射封装
举个例子
查询数据库所有账户信息到Account实体中
public class JdbcTemplateTest {
@Test
public void testFindAll() throws Exception {
// 创建核心对象
JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());
// 编写sql
String sql = "select * from account";
// 执行sql
List<Account> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>
(Account.class));
}
}
2.Spring整合JdbcTemplate
需求
基于Spring的xml配置实现账户的CRUD案例
步骤分析
- 创建java项目,导入坐标
- 编写Account实体类
- 编写AccountDao接口和实现类
- 编写AccountService接口和实现类
- 编写spring核心配置文件
- 编写测试代码
①创建java项目,导入坐标
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency><dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
</dependencies>
②编写Account实体类
public class Account {
private Integer id;
private String name;
private Double money;
get/set方法
toString方法
}
③编写AccountDao接口和实现类
public interface AccountDao {
public List<Account> findAll();
public Account findById(Integer id);
public void save(Account account);
public void update(Account account);
public void delete(Integer id);
}
@Repository
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//查询所有账户
public List<Account> findAll() {
//需要用到JDBCTemplate
// 编写sql
String sql = "select * from account";
// 执行sql
List<Account> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
return list;
}
public Account findById(Integer id) {
// 编写sql
String sql = "select * from account where id = ?";
// 执行sql
Account account = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Account>(Account.class), id);
return account;
}
public void save(Account account) {
// 编写sql
String sql = "insert into account values(null,?,?)";
// 执行sql
jdbcTemplate.update(sql, account.getName(), account.getMoney());
}
public void update(Account account) {
// 编写sql
String sql = "update account set name = ?,money = ? where id = ?";
// 执行sql
jdbcTemplate.update(sql, account.getName(), account.getMoney(),account.getId());
}
public void delete(Integer id) {
// 编写sql
String sql = "delete from account where id = ?";
// 执行sql
jdbcTemplate.update(sql, id);
}
}
④编写AccountService接口和实现类
public interface AccountService {
public List<Account> findAll();
public Account findById(Integer id);
public void save(Account account);
public void update(Account account);
public void delete(Integer id);
}
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public List<Account> findAll() {
List<Account> list = accountDao.findAll();
return list;
}
public Account findById(Integer id) {
Account account = accountDao.findById(id);
return account;
}
public void save(Account account) {
accountDao.save(account);
}
public void update(Account account) {
accountDao.update(account);
}
public void delete(Integer id) {
accountDao.delete(id);
}
}
⑤编写spring核心配置文件
<?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">
<!--开启注解扫描-->
<context:component-scan base-package="com.spring"/>
<!--引入properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--dataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置JdbcTemplate-->
<bean id="JdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"/>
</bean>
</beans>
⑥编写测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class AccountServiceTest {
@Autowired
private AccountService accountService;
@Test
public void testFindAll(){
List<Account> list = accountService.findAll();
for (Account account : list) {
System.out.println(account);
}
}
@Test
public void testFindById() {
Account account = accountService.findById(3);
System.out.println(account);
}
@Test
public void testSave() {
Account account = new Account();
account.setName("lucy");
account.setMoney(100d);
accountService.save(account);
}
@Test
public void testUpdate() {
Account account = new Account();
account.setId(4);
account.setName("rose");
account.setMoney(2000d);
accountService.update(account);
}
@Test
public void testDelete() {
accountService.delete(4);
}
}
3. 实现转账案例
步骤分析
- 创建java项目,导入坐标
- 编写Account实体类
- 编写AccountDao接口和实现类
- 编写AccountService接口和实现类
- 编写spring核心配置文件
- 编写测试代码
①创建java项目,导入坐标
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
</dependencies>
②编写Account实体类
public class Account {
private Integer id;
private String name;
private Double money;
get/set方法
toString
}
③编写AccountDao接口和实现类
public interface AccountDao {
public void out(String outUser, Double money);
public void in(String inUser, Double money);
}
@Repository
public class AccountDaoImpl implements AccountDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//转出
public void out(String outUser, Double money) {
String sql = "update account set money = money - ? where name = ?";
jdbcTemplate.update(sql, money, outUser);
}
//转入
public void in(String inUser, Double money) {
String sql = "update account set money = money + ? where name = ?";
jdbcTemplate.update(sql, money, inUser);
}
}
④编写AccountService接口和实现类
public interface AccountService {
//转账
public void transfer(String outUser, String inUser, Double money);
}
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public void transfer(String outUser, String inUser, Double money) {
accountDao.out(outUser,money);
accountDao.in(inUser,money);
}
}
⑤编写spring核心配置文件
<?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">
<!--开启注解扫描-->
<context:component-scan base-package="com.spring"/>
<!--引入properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置DataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
</beans>
⑥编写测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class AccountTest {
@Autowired
private AccountService accountService;
@Test
public void testTransfer() throws Exception {
accountService.transfer("tom", "jerry", 100d);
}
}
十六、Spring的事务
1.Spring中的事务控制方式
Spring的事务控制可以分为编程式事务控制和声明式事务控制。
- 编程式
开发者直接把事务的代码和业务代码耦合到一起,在实际开发中不用。 - 声明式
开发者采用配置的方式来实现的事务控制,业务代码与事务代码实现解耦合,使用的AOP思想。
2.编程式事务控制相关对象
①PlatformTransactionManager
PlatformTransactionManager接口,是spring的事务管理器,里面提供了我们常用的操作事务的方法
注意
- PlatformTransactionManager 是接口类型,不同的 Dao 层技术则有不同的实现类。
- Dao层技术是jdbcTemplate或mybatis时:
DataSourceTransactionManager- Dao层技术是hibernate时:
HibernateTransactionManager- Dao层技术是JPA时:
JpaTransactionManager
②TransactionDefinition
TransactionDefinition接口提供事务的定义信息(事务隔离级别、事务传播行为等等)
a.事务隔离级别
设置隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读和虚读(幻读)
- ISOLATION_DEFAULT 使用数据库默认级别
- ISOLATION_READ_UNCOMMITTED 读未提交
- ISOLATION_READ_COMMITTED 读已提交
- ISOLATION_REPEATABLE_READ 可重复读
- ISOLATION_SERIALIZABLE 串行化
b.事务传播行为
事务传播行为指的就是当一个业务方法【被】另一个业务方法调用时,应该如何进行事务控制。
- read-only(是否只读):建议查询时设置为只读
- timeout(超时时间):默认值是-1,没有超时限制。如果有,以秒为单位进行设置
③TransactionStatus
TransactionStatus 接口提供的是事务具体的运行状态。
可以简单的理解三者的关系:事务管理器通过读取事务定义参数进行事务管理,然后会产生一系列的事务状态。
④实现代码
a.配置文件
<!--事务管理器交给IOC-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
b.业务层代码
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Autowired
private PlatformTransactionManager transactionManager;
@Override
public void transfer(String outUser, String inUser, Double money) {
// 创建事务定义对象
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// 设置是否只读,false支持事务
def.setReadOnly(false);
// 设置事务隔离级别,可重复读mysql默认级别
def.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
// 设置事务传播行为,必须有事务
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
// 配置事务管理器
TransactionStatus status = transactionManager.getTransaction(def);
try {
// 转账
accountDao.out(outUser, money);
accountDao.in(inUser, money);
// 提交事务
transactionManager.commit(status);
} catch (Exception e) {
e.printStackTrace();
// 回滚事务
transactionManager.rollback(status);
}
}
}
⑤知识小结
Spring中的事务控制主要就是通过这三个API实现的
- PlatformTransactionManager 负责事务的管理,它是个接口,其子类负责具体工作
- TransactionDefinition 定义了事务的一些相关参数
- TransactionStatus 代表事务运行的一个实时状态
理解三者的关系:事务管理器通过读取事务定义参数进行事务管理,然后会产生一系列的事务状态。
3.基于XML的声明式事务控制
在 Spring 配置文件中声明式的处理事务来代替代码式的处理事务。底层采用AOP思想来实现的。
声明式事务控制明确事项:
- 核心业务代码(目标对象) (切入点是谁?)
- 事务增强代码(Spring已提供事务管理器))(通知是谁?)
- 切面配置(切面如何配置?)
①快速入门
需求
使用spring声明式事务控制转账业务。
步骤分析
- 引入tx命名空间
- 事务管理器通知配置
- 事务管理器AOP配置
- 测试事务控制转账业务代码
a.引入tx命名空间
<?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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
b.事务管理器通知配置
<!--事务管理器对象-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--通知增强-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--定义事务的一些属性 *表示当前任意名称的方法都走默认配置-->
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
c.事务管理器AOP配置
<!--aop配置:配置切面-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.spring.service.impl.AccountServiceImpl.*(..))"/>
</aop:config>
d.测试事务控制转账业务代码
@Override
public void transfer(String outUser, String inUser, Double money) {
accountDao.out(outUser, money);
// 制造异常
int i = 1 / 0;
accountDao.in(inUser, money);
}
②事务参数的配置详解
<!--通知增强-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--定义事务的一些属性 *表示当前任意名称的方法都走默认配置
name:切点方法名称
isolation:事务的隔离级别
propagation:事务的传播行为
timeout:超时时间
read-only:是否只读 -->
<tx:attributes>
<tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" timeout="-1"/>
</tx:attributes>
</tx:advice>
CRUD常用配置
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
③知识小结
- 平台事务管理器配置
- 事务通知的配置
- 事务aop织入的配置
4.基于注解的声明式事务控制
①常用注解
步骤分析
- 修改service层,增加事务注解
- 修改spring核心配置文件,开启事务注解支持
a.修改service层,增加事务注解
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ,timeout = -1,readOnly = false)
public void transfer(String outUser, String inUser, Double money) {
accountDao.out(outUser,money);
//int i = 1/0;
accountDao.in(inUser,money);
}
}
b.修改spring核心配置文件,开启事务注解支持
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w2.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.spring"/>
<!--引入properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置DataSource-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--事务的注解支持-->
<tx:annotation-driven/>
</beans>
②纯注解
核心配置类
@Configuration //声明该类为核心配置类
@ComponentScan("com.lagou") //包扫描
@Import(DataSourceConfig.class) //导入其他配置类
@EnableTransactionManagement //事务的注解驱动
public class SpringConfig {
@Bean
public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource){
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
return jdbcTemplate;
}
@Bean
public PlatformTransactionManager getPlatformTransactionManager(@Autowired DataSource dataSource){
DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
return dataSourceTransactionManager;
}
}
数据源配置类
@PropertySource("classpath:jdbc.properties") //引入properties文件
public class DataSourceConfig {
@Value("${jdbc.driverClassName}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean //会把当前方法的返回值对象放进IOC容器中
public DataSource getDataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driver);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
}
③知识小结
- 平台事务管理器配置(xml、注解方式)
- 事务通知的配置(@Transactional注解配置)
- 事务注解驱动的配置 < tx:annotation-driven/>、@EnableTransactionManagement
十七、Spring集成web环境
1.ApplicationContext应用上下文获取方式
应用上下文对象是通过 new ClasspathXmlApplicationContext(spring配置文件) 方式获取的,但是每次从容器中获得Bean时都要编写 new ClasspathXmlApplicationContext(spring配置文件) ,这样的弊端是配置文件加载多次,应用上下文对象创建多次。
解决思路分析:
在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到最大的域servletContext域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象了。
2.Spring提供获取应用上下文的工具
上面的分析不用手动实现,Spring提供了一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。
所以我们需要做的只有两件事:
- 在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
- 使用WebApplicationContextUtils获得应用上下文对象ApplicationContext
3.实现
①导入Spring集成web的坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
</dependencies>
②配置ContextLoaderListener监听器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>AccountServlet</servlet-name>
<servlet-class>com.spring.servlet.AccountServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AccountServlet</servlet-name>
<url-pattern>/AccountServlet</url-pattern>
</servlet-mapping>
<!-- 配置全局参数:指定applicationContext文件的路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置spring监听器contextLoaderListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
③通过工具获得应用上下文对象
public class AccountServlet extends javax.servlet.http.HttpServlet {
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
doGet(request,response);
}
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
/*ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
Account account = (Account) classPathXmlApplicationContext.getBean("account");
System.out.println(account);*/
ApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
Account account = (Account) webApplicationContext.getBean("account");
System.out.println(account);
}
}