1 Spring
1.1简介
- Spring 给软件行业带来了春天
- 2002 首次推出了 Spring框架的雏形 interface21框架
- 2004年3月24日 以 interface21框架为基础 发布Spring
- Spring的理念 使现有的技术更加容易使用 本身是一个大杂烩 整合了现有的技术框架
2.2 2个框架
- SSH Struct2+Spring+Hibernate
- SSM SpringMVC+Spring+Mybatis
官网 https://spring.io/
下载地址 Maven
https://mvnrepository.com/artifact/org.springframework/spring-webmvc
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
1.3 优点
- Spring是一个开元的免费的框架(容器)
- Spring是一个轻量级 非入侵式的框架
- 控制反转(IOC) 面向切面编程(AOP)
- 支持事务处理
- 对框架的整合支持
Spring就是一个轻量级的控制反转(IOC) 面向切面编程(AOP)的框架!!!
1.4 组成
1.5 拓展
在Spring的官方有这个介绍 现代化的Java开发 说白了就是基于Spring的开发
- SpringBoot
- 一个快速开发的脚手架
- 基于Spring Boot可以快速的可开发单个微服务
- 约定大于配置
- SpringCloud
- SpringCloud是基于SpringBoot实现的
因为现在大多数攻速都在使用SpringBoot进行快速开发 学习SpringBoot前提 需要完全掌握Spring以及SpringMVC 承上启下的作用
弊端 发展了太久 违背了原来的理念 配置十分繁琐 配置地狱
2 IOC理论推导
-
UserDao接口
package com.lhc.dao; public interface UserDao { void getUser(); }
-
UserDaoImpl实现类
package com.lhc.dao; public class UserDaoImpl implements UserDao { public void getUser() { System.out.println("默认获取用户的数据"); } }
package com.lhc.dao; public class UserDaoMySQLImpl implements UserDao { public void getUser() { System.out.println("获取mysql"); } }
package com.lhc.dao; public class UserDaoSQLserverImpl implements UserDao { public void getUser() { System.out.println("调用了SQLserver"); } }
-
UserService接口
package com.lhc.service; public interface UserService { void getUser(); }
-
UserService业务实现类
package com.lhc.service; import com.lhc.dao.UserDao; import com.lhc.dao.UserDaoImpl; public class UserServiceImpl implements UserService { //先前我们直接指明实现类 这里的 new UserDaoImpl()是可以不写的 //我们在之后controller层可以set更改要用实现类 private UserDao userDao =new UserDaoImpl(); //现在我们 利用set进行对待实现值的注入 可以在controller层选择实现类 public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void getUser() { userDao.getUser(); } }
-
Controller
import com.lhc.dao.UserDaoImpl; import com.lhc.dao.UserDaoMySQLImpl; import com.lhc.dao.UserDaoSQLserverImpl; import com.lhc.service.UserServiceImpl; public class Mytest { public static void main(String[] args) { //用户实际调用的是业务层 dao层他们不需要解除 UserServiceImpl userService = new UserServiceImpl(); userService.setUserDao(new UserDaoMySQLImpl()); userService.getUser(); userService.setUserDao(new UserDaoImpl()); userService.getUser(); userService.setUserDao(new UserDaoSQLserverImpl()); userService.getUser(); } }
在我们之前的业务中 用户的需求可能会影响我们原来的代码 我们需要根据用户的需求 去修改原代码 如果程序代码量十分大 修改一次的成本十分大
我们使用一个Set接口实现
//利用set进行对待实现值的注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
- 之前 是程序主动创建对象 控制权在程序员手上
- 使用了set注入 程序不在具有主动性 而是变成了被动的接受对象
这种思想 从本质上解决了问题 我们程序员再也不用去管理对象的创建了 系统的耦合性大大的降低 可以更加专注业务的实现 这是IOC的原型
IOC本质
控制反转IoC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现IoC的一种方法,也有人认为DI只是IoC的另一种说法。没有IoC的程序中 , 我们使用面向对象编程 , 对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,个人认为所谓控制反转就是:获得依赖对象的方式反转了。
3 HelloSpring
对象由Spring来创建 管理 装配
spring 文档 https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html
spring 中文文档https://www.docs4dev.com/docs/zh/spring-framework/5.1.3.RELEASE/reference/core.html#beans
配置文件
<?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包之后 已经自动生成 不需要这样配置)
如何类里旁边没有绿色的豆子(表明已经放入Spring容器)
4 Spring
4.1 别名
<!--别名 如果添加了别名 我们也可以使用别名获取到这个对象-->
<alias name="user" alias="user2"/>
4.2 Bean的配置
<!--
id bean的唯一标识符 也就是相当于我们学的对象名
class bean对象所对应的全限定名 包名+类型
name 也就是别名 可以同时取多个别名
-->
<bean id="user" class="com.lhc.pojo.User" name ="user2 user3,user4;user5">
<property name="name" value="Spring"/>
</bean>
4.3 import
这个一般用于团队开发使用 他可以将多个配置文件 导入合并为一个
假设那种项目中有多个人开发 这三个人赋值不同的类开发 不同的类需要注册在不同的bean中 我们可以利用import将所有人的beans.xml合并为一个总的
- 张三
- 李四
- 王五
<import resource="11.xml"/>
<import resource="22.xml"/>
如果内容11.xml和22.xml里面有相同的类 会报错 也可能不报错 但是尽量不要重复
5 依赖注入
5.1构造器注入
下面的前提是 你的类已经创建了set 和构造函数 本质是调用他们 在spring里创建
-
使用无参构造方法创建对象
<bean id="user" class="com.lhc.pojo.User"> <property name="name" value="林宏程"/> </bean>
-
假设我们要使用有参构造方法创建对象
-
下标赋值
<!--下标赋值--> <bean id="user" class="com.lhc.pojo.User"> <constructor-arg index="0" value="有参构造"/> </bean>
-
类型赋值
<!--不建议用 如果有2个相同类型就会混乱--> <bean id="user" class="com.lhc.pojo.User"> <constructor-arg type="java.lang.String" value="林宏程"/> </bean>
-
参数名赋值
<!--参数名赋值--> <bean id="user" class="com.lhc.pojo.User"> <constructor-arg name="name" value="lhc"/> </bean>
-
关于容器里的对象
在配置文件加载的时候 容器中管理的对象就已经初始化了(被创建了) 而且实例的对象从Spring拿出的是同一个对象
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">
<bean id="user" class="com.lhc.pojo.User">
<property name="name" value="林宏程"/>
</bean>
<bean id="userT" class="com.lhc.pojo.UserT">
</bean>
</beans>
测试
public class myTest {
public static void main(String[] args) {
//Spring容器 读取xml配置文件的时候 就已经把所有的对象都创建了 而且Spring创建的实例 就是同一个对象
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user1 = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
System.out.println(user1==user2);//true
}
}
5.2 Set方式注入
- 依赖注入 Set注入
- 依赖 bean对象的创建依赖于容器
- 注入 bean对象的所有属性 由容器来注入
- Lombok如果用不了 去IDEA setting里下载插件
[环境搭建]
-
复杂类型
package com.lhc.pojo; import lombok.AllArgsConstructor; import lombok.Data; @AllArgsConstructor @NoArgsConstructor @Data public class Address { private String address; }
-
真实测试类型
package com.lhc.pojo; import lombok.AllArgsConstructor; import lombok.Data; import java.util.*; @NoArgsConstructor @AllArgsConstructor @Data public class Student { private String name; private Address address; private String[] books; private List<String> hobbies; private Map<String,String> card; private Set<String> games; private Properties info; private String wife; }
-
beans.xml
<bean id="student" class="com.lhc.pojo.Student"> <!--第一种 普通注入--> <property name="name" value="林宏程"/> </bean>
-
测试类
import com.lhc.pojo.Student; import org.springframework.context.support.ClassPathXmlApplicationContext; public class myTest { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); Student student = (Student)context.getBean("student"); System.out.println(student.getName()); } }
-
完善注入信息
<bean class="com.lhc.pojo.Address" name="address"> <property name="address" value="瑞安"/> </bean> <bean id="student" class="com.lhc.pojo.Student"> <!--第一种 普通注入--> <property name="name" value="林宏程"/> <!--第二种注入 bean注入 ref--> <property name="address" ref="address"/> <!--数组--> <property name="books"> <array> <value>红楼梦</value> <value>西游记</value> <value>三国演义</value> <value>水浒传</value> </array> </property> <!--List--> <property name="hobbies"> <list> <value>听歌</value> <value>敲代码</value> <value>看电影</value> </list> </property> <!--Map--> <property name="card"> <map> <entry key="身份证" value="123456789"/> <entry key="银行卡" value="987654321"/> </map> </property> <!--Set--> <property name="games"> <set> <value>LOL</value> <value>BOB</value> <value>COC</value> </set> </property> <!--null注入--> <property name="wife"> <null></null> </property> <!--Properties--> <property name="info"> <props> <prop key="姓名">小明</prop> <prop key="性别">男</prop> <prop key="学号">20190525</prop> </props> </property> </bean> </beans>
5.3 拓展方式注入
我们可以使用P命名空间和C命名空间注入
<?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:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--P命名空间注入 可以直接注入属性的值 property-->
<bean id="user" class="com.lhc.pojo.User" p:age="15" p:name="林宏程"/>
<!--C命名空间注入 通过构造器注入 Constructor-->
<bean id="user" class="com.lhc.pojo.User" c:age="18" p:name="林宏程"/>
</beans>
注意点 p命名和c命名空间 不能直接使用 需要导入约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
测试
从测试得知 如果bean创建了2个 那么对象也不是同一个对象了 而且 p命名和c命名空间 不可以在同一个bean里复用
@Test
public void test(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("usersbean.xml");
User user1 = context.getBean("user1", User.class);
User user2 = context.getBean("user2", User.class);
System.out.println(user1);
System.out.println(user2);
System.out.println(user1==user2);
//User(name=林宏程, age=15)
//User(name=林宏程, age=18)
//false
}
5.4 bean的作用域
-
单例模式(Spring的默认机制)
每次从容器中get的时候 都是同一个对象
<bean id="user2" class="com.lhc.pojo.User" c:age="18" c:name="林宏程" scope="singleton"/>
@Test public void test(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("usersbean.xml"); User user2 = context.getBean("user1", User.class); User user3 = context.getBean("user1", User.class); System.out.println(user3==user2); //true }
-
原型模式
每次从容器中get的时候 都会产生一个新的对象
<bean id="user2" class="com.lhc.pojo.User" c:age="18" c:name="林宏程" scope="prototype"/>
@Test public void test(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("usersbean.xml"); User user2 = context.getBean("user2", User.class); User user3 = context.getBean("user2", User.class); System.out.println(user3==user2); //false }
-
其余的request session application 只能在web开发中使用到
6 Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找 并自动装配bean的属性
有三种装配的方式
- 在XML显示的配置
- 在java中显示配置
- 隐式的自动装配bean
环境搭配
一个人有两个宠物
package com.lhc.pojo;
public class Cat {
public void shout(){
System.out.println("喵喵喵");
}
}
package com.lhc.pojo;
public class Dog {
public void shout(){
System.out.println("汪汪汪");
}
}
package com.lhc.pojo;
import lombok.Data;
@Data
public class Person {
private String name;
private Dog dog;
private Cat cat;
}
6.1使用 autowire=""
1 byName的自动装配
byName
会自动在上下文中查找 和自己对象Set方法后面的值对应的bean
比如Person里成员名叫 cat 而上面设置的id正好也是cat 如果id是cat11 对不上就装配不了了
<bean class="com.lhc.pojo.Cat" id="cat"/>
<bean class="com.lhc.pojo.Dog" id="dog"/>
<bean class="com.lhc.pojo.Person" id="person" autowire="byName">
<property name="name" value="林宏程"/>
</bean>
2 byType的自动装配
byType
会自动在上下文中查找 和自己对象属性类型相同的bean
比如Person里面有个成员类型是Cat 正好也有个Cat类型的bean 就会自动装配 但是id必须保持一致 也可以选择不写id
<bean class="com.lhc.pojo.Cat" id="cat"/>
<bean class="com.lhc.pojo.Dog" id="dog"/>
<bean class="com.lhc.pojo.Person" id="person" autowire="byType">
<property name="name" value="林宏程"/>
</bean>
3 测试
@Test
public void test1(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = context.getBean("person", Person.class);
person.getCat().shout();
person.getDog().shout();
}
}
4 小结
- byName的时候 需要保证所有bean的id唯一 并且这个bean需要和自动注入的属性的set方法的值一致
- byType的时候 需要保证所有bean的Class唯一 并且这个bean需要和自动注入的类型一致
6.2 使用注解
jdk1.5支持的注解
Spring2.5就支持注解了
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解支持-->
<context:annotation-config/>
</beans>
要用注解须知
-
导入约束 context约束
-
配置注解的支持 <context:annotation-config/> 重要!
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!--开启注解支持--> <context:annotation-config/> <bean class="com.lhc.pojo.Cat" id="cat"/> <bean class="com.lhc.pojo.Dog" id="dog1"/> <bean class="com.lhc.pojo.Dog" id="dog2"/> <bean class="com.lhc.pojo.Dog" id="dog3"/> <bean class="com.lhc.pojo.Person" id="person"/> </beans>
1 @Autowired
相当于byName
直接在属性上使用即可 也可以在set方式上使用
使用**@Autowired** 我们可以不用编写set方法 前提是你这个自动装配的属性在IOC(Spring)容器中存在
他会先匹配类型 class="com.lhc.pojo.Dog"是否一致 然后再匹配id="dog"是否一致 两者必须都一致
如下代码
<bean class="com.lhc.pojo.Dog" id="dog"/>
对应下面的
@Autowired
private Dog dog;
private Dog dog; 和class=“com.lhc.pojo.Dog” 都是Dog
private Dog dog;和id=“dog” 都是dog
如果id不符合 这个时候就需要 @Qualifier(value = “XXX”)
@Qualifier(value = “XXX”)
配合**@Autowired**使用 可以去匹配特定的bean的id 如下 没有一个对应dog这个属性名 找不到 就让他找特定的id
<bean class="com.lhc.pojo.Cat" id="cat"/>
<bean class="com.lhc.pojo.Dog" id="dog1"/>
<bean class="com.lhc.pojo.Dog" id="dog2"/>
<bean class="com.lhc.pojo.Dog" id="dog3"/>
<bean class="com.lhc.pojo.Person" id="person"/>
这个时候在对象里加入 @Qualifier(value = “dog2”) 就会去匹配那个dog2的id的bean
public class Person {
private String name;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;
@Autowired
private Cat cat;
}
2 @Resource
相当于byType
@Resource和**@Autowired**有点不一样 他可以不写id 或者一致
他会匹配类型 class="com.lhc.pojo.Dog"是否一致 然后再看id是否一致 或者不存在
代码如下
<bean class="com.lhc.pojo.Cat" id="cat"/>
对应下面的
@Resource
private Dog dog;
class="com.lhc.pojo.Dog"和private Dog dog 都是Dog类
需要id一致或者直接不写
但是有多个Dog 或者 id不一致的时候 这个时候就需要 @Resource(name = “XXX”)
@Resource(name = “XXX”)
配合**@Resource**使用 可以去匹配特定的bean的Class 如下如果有多个Dog类 @Resource可能会找不到要用那个
<bean class="com.lhc.pojo.Cat" id="cat"/>
<bean class="com.lhc.pojo.Dog" id="dog1"/>
<bean class="com.lhc.pojo.Dog" id="dog2"/>
<bean class="com.lhc.pojo.Dog" id="dog3"/>
<bean class="com.lhc.pojo.Person" id="person"/>
这个时候在对象里加入 @Resource(name = “dog1”) 就会去匹配那个dog1的id的bean
public class Person {
private String name;
@Resource(name = "dog1")
private Dog dog;
@Autowired
private Cat cat;
}
3 测试
@Test
public void test1(){
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = context.getBean("person", Person.class);
person.getCat().shout();
person.getDog().shout();
}
}
4 小结
@Autowired和@Resource
相同点
- 都是用来自动装配的 都可以放在属性字段上
不同点
-
@Autowired他必须保证Class和Id都一致(建议使用)
-
@Resource 他可以让id为空 但是必须保证Class一致并且唯一(不建议使用)
-
@Autowired通过 byName实现
-
@Resource 通过 byType实现
在使用的时候个人认为@Autowired更加符合规范 Id不写阅读性比较差
6.3 注解和autowire的区别
注解
可以更改匹配的id 如果cat对不上cat1 cat2 cat3 我们必须用注解 @Resource(name = “XXX”)或者@Qualifier(value = “XXX”)
autowire
不能更改对应的id 用了cat 就必须对应id是cat
7 使用注解开发
在spring4之后 要使用注解开发 必须要保证AOP的包导入
在使用注解需要导入context约束 增加注解的支持
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解支持-->
<context:annotation-config/>
</beans>
-
bean
//等价于 <bean id="user" class="com.lhc.pojo.User"/> //@Component 组件 @Component public class User { public String name; }
-
属性注入
对应 5.依赖注入
@Component public class User { //相当于 <property name="name" value="Mercy"/> @Value("Mercy") public String name; //也可以放这里 @Value("Mercy") public void setName(String name) { } }
-
衍生的注解
@Component有几个衍生注解 我们在web开发中 按照mvc三层架构分层
- dao [@Repository]
- service [@Service]
- servlet [@Controller]
这四个注解功能都是一样的 都是将某个类注册到Spring中 装配Bean
-
自动装配
对应 6.Bean的自动装配
@Autowired
@Nullable
@Resource
@Component
-
作用域
@Scope("prototype") //原型模式 public class User
-
小结
xml与注解
- xml更加万能 适用任何场景 维护方便
- 注解 不是自己的类使用不了 维护复杂
xml和注解最佳实践
- xml用来管理bean
- 注解值负责完成属性的注入
- 我们在使用的过程中 只需要注意 必须让注解生效 就需要开启注解的支持
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--开启注解支持--> <context:annotation-config/> <!--指定要扫描的包 这个报下的注解就会生效--> <context:component-scan base-package="com.lhc"/> </beans>
8 使用Java的方式配置Spring
我们现在要完全不使用Spring的xml配置了 全权交给Java来做
JavaConfig 是Spring的子项目 在Spring4之后 它成为了一个核心功能
实体类
package com.lhc.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
//这个注解的意思 就是说明这个类被Spring接管了 注册到了容器中
@Component
public class User {
public String name;
public String getName() {
return name;
}
@Value("mercy")//属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
配置文件
package com.lhc.config;
import com.lhc.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//这个也会被Spring容器托管 注册到容器中 因为他本来就是个@Component
// @Configuration代表这是一个配置类 就和我们之前看的beans.xml一样
@ComponentScan("com.lhc.pojo")
@Configuration
public class lhcconfig {
//注册一个bean 就相当于我们之前写的一个bean标签
//这个方法的名字 就相当于bean标签中的id
//这个方法的返回值 就相当于bean标签中的Class
@Bean
public User user(){
return new User();//就是返回要注入到bean的对象
}
}
测试
import com.lhc.config.lhcconfig;
import com.lhc.pojo.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class myTest {
public static void main(String[] args) {
//如果完全使用了配置类方式去做 我们就只能通过AnnotationConfig 上下文获取容器 通过配置类的class对象加载
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(lhcconfig.class);
User user = context.getBean("user", User.class);
System.out.println(user.name);
}
}
这种纯Java的配置方式 在SpringBoot中随处可见
9 代理模式
为什么要学习代理模式?
因为这就是SpringAOP的底层
代理模式的分类
- 静态代理
- 动态代理
9.1 静态代理
代码步骤
1.接口(租房子)
package com.lhc.demo01;
public interface Rent {
void rent();
}
2.真实角色(房东)
package com.lhc.demo01;
//房东
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租房子");
}
}
3代理角色(中介)
package com.lhc.demo01;
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
public void rent() {
seeHouse();
host.rent();
hetong();
fare();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房子");
}
//收中介费
public void fare(){
System.out.println("收中介费");
}
//签合同
public void hetong(){
System.out.println("签合同");
}
}
4.客户访问代理角色(客户)
package com.lhc.demo01;
public class Client {
public static void main(String[] args) {
//直接找房东
Host host = new Host();
host.rent();
//代理 中介帮房东租房子 但是呢 代理角色一般会有一些附属操作
Proxy proxy = new Proxy(host);
//不需要面对向东 直接找中介租房即可
proxy.rent();
}
}
角色分析
- 抽象角色 一般会使用接口 或者抽象类来解决
- 真实角色 被代理的角色
- 代理角色 代理真实的角色 之后一般会做一些附属操作
- 客户 访问代理对象的人
代理模式的好处
- 可以让真实角色的操作更加纯粹 不用去关注一些公共的业务
- 公共也就交给了代理角色 实现了业务的分工
- 公共业务发生扩展的时候 方便集中管理
代理模式的坏处
- 一个真实角色就会产生一个代理角色 代码量会翻倍 开发效率会遍地
9.2 加深理解
常见 客户增删改查实现后 又需要增加新的日志项目
1.接口(实现的增删改查)
package com.lhc.demo02;
public interface UserService {
void add();
void delete();
void update();
void query();
}
2.增删改查实现
package com.lhc.demo02;
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增加一个用户");
}
public void delete() {
System.out.println("删除一个用户");
}
public void update() {
System.out.println("更新一个用户");
}
public void query() {
System.out.println("查询一个用户");
}
}
3.代理角色
package com.lhc.demo02;
public class UserServiceProxy implements UserService {
private UserServiceImpl userService;
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
public UserServiceProxy() {
}
public void add() {
log("add");
userService.add();
}
public void delete() {
log("delete");
userService.delete();
}
public void update() {
log("update");
userService.update();
}
public void query() {
log("query");
userService.query();
}
//日志方法
public void log(String msg){
System.out.println("使用了"+msg+"方法");
}
}
4.客户
package com.lhc.demo02;
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy();
proxy.setUserService(userService);
proxy.add();
}
}
个人总结
代理模式本质就是为了不改变 原有的代码块同时编写新的代码
原来的程序员写了一个基础的增删改查 如果实现的代码非常复杂 我们在新增功能的时候影响到老代码的功能 这个时候 我们就需要代理模式创建一个代理 让代理先实现原有的方法 然后再另外写新功能的代码
9.3 动态代理
- 动态代理和静态代理角色一样
- 动态代理的代理类 是动态生成的 静态代理我们直接写好的
- 动态代理分为两大类 基于接口的动态代理 基于类的动态代理
- 基于接口—JKD动态代理 {我们在这里使用}
- 基于类 java字节码实现 javasist
需要了解两个类 Proxy 代理 InvocationHandler 调用处理程序
动态代理好处
- 可以让真实角色的操作更加纯粹 不用去关注一些公共的业务
- 公共也就交给了代理角色 实现了业务的分工
- 公共业务发生扩展的时候 方便集中管理
- 一个动态代理类 代理的是一个接口 一般就是一类业务
- 一个动态代理类可以代理多个类 只要是实现了同一个接口即可
万能动态代理
动态代理类
package com.lhc.demo04;
import com.lhc.demo03.Rent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//等我们会用这个类 自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
}
//处理代理实例 并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
//动态代理的本质 就是使用反射机制实现
Object result = method.invoke(target, args);
return result;
}
public void log(String msg){
System.out.println("执行了"+msg+"方法");
}
}
客户
package com.lhc.demo04;
import com.lhc.demo02.UserService;
import com.lhc.demo02.UserServiceImpl;
public class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色 不存在 这个是为了实现动态类 生成的类
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService);//设置代理对象
//动态生成代理类
UserService proxy = (UserService)pih.getProxy();
proxy.delete();
}
}
个人总结
动态代理存在的意义是 静态代理如果想要代理一个真实角色 他需要继承一个接口 但是如果你要代理两个角色就需要写2个代理 如果你一个代理实现了2个接口 那么就会实现2个真实对象
加入了动态代理 就相当于你给我什么接口 我就用什么接口
也就是
public class UserServiceProxy implements UserService
这里的UserService 我使用动态代理就是可变的
而且要实现这个功能我们就需要 两个类 Proxy 代理 InvocationHandler
首先我们客户用pih.setTarget(userService); 就获得了要代理的真实角色
//真实角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色 不存在 这个是为了实现动态类 生成的类
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService);//设置代理对象
Proxy 这个时候就会帮我们生成一个这个真实角色的代理
如下是这个方法如何实现的代码
//被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), target.getClass().getInterfaces(),this);
}
之后nvocationHandler需要重写invoke这个方法
帮我们我们实现如何得到真实角色的全部方法
//处理代理实例 并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable{
//动态代理的本质 就是使用反射机制实现
Object result = method.invoke(target, args);
return result;
//在这个代码块中 我们可以插入我们需要加入的新功能
}
这里的method.invoke()方法里放入target(要代理的真实对象),args(他的方法需要的参数) 这个是写死的 底层原理还深究
实际在客户类调用的时候 我们只需要
//动态生成代理类
UserService proxy = (UserService)pih.getProxy();
这里的proxy对象里已经拥有代理真实对象的所有方法了 这里我们只需要用里面有的 delete() 方法就可以了
proxy.delete();
10 AOP
10.1 什么是AOP
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
10.2 Aop在Spring中的作用
提供声明式事务;允许用户自定义切面
以下名词需要了解下:
横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志 , 安全 , 缓存 , 事务等等 …
切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
目标(Target):被通知对象。
代理(Proxy):向目标对象应用通知之后创建的对象。
切入点(PointCut):切面通知 执行的 “地点”的定义。
连接点(JointPoint):与切入点匹配的执行点。
即 Aop 在 不改变原有代码的情况下 , 去增加新的功能
10.3 使用Spring实现Aop
【重点】使用AOP切入,需要导入一个依赖包!
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
方式一 使用Spring的API接口
第一种方式
通过 Spring API 实现
首先编写我们的业务接口和实现类
public interface UserService {
public void add();
public void delete();
public void update();
public void search();
}
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加用户");
}
@Override
public void delete() {
System.out.println("删除用户");
}
@Override
public void update() {
System.out.println("更新用户");
}
@Override
public void search() {
System.out.println("查询用户");
}
}
然后去写我们的增强类 , 我们编写两个 , 一个前置增强 一个后置增强
public class BeforeLog implements MethodBeforeAdvice {
//method : 要执行的目标对象的方法
//objects : 被调用的方法的参数
//O : 目标对象
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName() + "的" + method.getName() + "方法被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue 返回值
//method被调用的方法
//args 被调用的方法的对象的参数
//target 被调用的目标对象
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了" + target.getClass().getName()
+"的"+method.getName()+"方法,"
+"返回值:"+returnValue);
}
}
最后去spring的文件中注册 , 并实现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">
<!--注册bean-->
<bean id="userService" class="com.kuang.service.UserServiceImpl"/>
<bean id="log" class="com.kuang.log.Log"/>
<bean id="afterLog" class="com.kuang.log.AfterLog"/>
<!--aop的配置-->
<aop:config>
<!--切入面 已经API接口写好了 所以不需要写-->
<!--切入点 expression:表达式匹配要执行的方法-->
<aop:pointcut id="pointcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/>
<!--执行环绕; advice-ref执行方法 . pointcut-ref切入点-->
<aop:advisor advice-ref="BeforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
测试
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//动态代理代理的是接口 注意点
UserService userService = (UserService) context.getBean("userService");
userService.search();
}
}
Aop的重要性 : 很重要 . 一定要理解其中的思路 , 主要是思想的理解这一块 .
Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理 .
方法二 自定义类实现AOP
目标业务类不变依旧是userServiceImpl
第一步 : 写我们自己的一个切入类
public class DiyPointcut {
public void before(){
System.out.println("---------方法执行前---------");
}
public void after(){
System.out.println("---------方法执行后---------");
}
}
去spring中配置
<!--第二种方式自定义实现-->
<!--注册bean-->
<bean id="diy" class="com.kuang.config.DiyPointcut"/>
<aop:config>
<!--自定义切面 ref要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.lhc.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:before method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
测试:
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
方式三 使用注解实现
第一步:编写一个注解实现的增强类
package com.kuang.config;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AnnotationPointcut {
@Before("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("---------方法执行前---------");
}
@After("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("---------方法执行后---------");
}
@Around("execution(* com.kuang.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
System.out.println("签名:"+jp.getSignature());
//执行目标方法proceed
Object proceed = jp.proceed();
System.out.println("环绕后");
System.out.println(proceed);
}
}
第二步:在Spring配置文件中,注册bean,并增加支持注解的配置
<!--方式三-->
<!--开启注解模式-->
<bean id="AnnotationPointCut" class="com.lhc.DiyPointCut.AnnotationPointCut"/>
<!--默认 proxy-target-class="false" cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy/>
11 整合Mybatis
步骤
- 导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关
- aop
- mybatis-spring{new}
- 编写配置文件
- 测试
11.1 回忆mybatis
- 编写实体类
- 编写核心配置文件
- 编写接口
- 编写mapper.xml
- 测试
11.2 Mybatis-Spring
官方文档 http://mybatis.org/spring/zh/transactions.html
导入包
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!--Spring操作数据库的话 还需要一个spring jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.19.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies>
<!--在build中配置resources 来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
方法一步骤
前3步都是在spring-dao.xml写的
1.编写数据源
<?xml version="1.0" encoding="UTF8"?>
<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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--DataSource 使用Spring的数据源 替代mybatis的配置 c3p0 adcp druid
我们这里使用Spring提供的JDBC org.springframework.jdbc.datasource.DriverManagerDataSource
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
</beans>
2.SqlSessionFactory
<!--sqlSessionFactory 工具类
org.mybatis.spring.SqlSessionFactoryBean
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定mybatis配置文件
可以把 mybatis-config.xml绑定在一起
可以把映射写上
-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/lhc/dao/*.xml"/>
</bean>
3.SqlSessionTemplate
<!--就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入org.mybatis.spring.SqlSessionTemplate 因为他没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
4.需要给接口加实现类
package com.lhc.dao;
import com.lhc.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
//我们的所有操作 在原来都使用sqlSession来执行 现在都使用sqlSessionTemplate
private SqlSessionTemplate sqlSessionTemplate;
public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
this.sqlSessionTemplate = sqlSessionTemplate;
}
public List<User> selectUser() {
UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
5.将自己写的实现类 注入到spring中
将上面的spring-dao.xml 导入到applicationContext.xml
<?xml version="1.0" encoding="UTF8"?>
<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">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.lhc.dao.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
</beans>
6.测试
import com.lhc.dao.UserMapper;
import com.lhc.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class mytest {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
方法二步骤
前3步都是在spring-dao.xml写的
1.编写数据源
<?xml version="1.0" encoding="UTF8"?>
<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
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--DataSource 使用Spring的数据源 替代mybatis的配置 c3p0 adcp druid
我们这里使用Spring提供的JDBC org.springframework.jdbc.datasource.DriverManagerDataSource
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url"
value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
</beans>
2.SqlSessionFactory
<!--sqlSessionFactory 工具类
org.mybatis.spring.SqlSessionFactoryBean
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定mybatis配置文件
可以把 mybatis-config.xml绑定在一起
可以把映射写上
-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/lhc/dao/*.xml"/>
</bean>
3.需要给接口加实现类
这里使用SqlSessionDaoSupport把SqlSessionTemplate给实现了 但是还是需要SqlSessionFactory才能实现SqlSessionTemplate 所以上面还是要配置SqlSessionTemplate
package com.lhc.dao;
import com.lhc.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
4.将自己写的实现类 注入到spring中
将上面的spring-dao.xml 导入到applicationContext.xml
虽然这里userMapper2 没有property 但是父类的SqlSessionDaoSupport 需要SqlSessionDaoSupport ,因此这里是给SqlSessionDaoSupport 传入SqlSessionDaoSupport
<?xml version="1.0" encoding="UTF8"?>
<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">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.lhc.dao.UserMapperImpl">
<property name="sqlSessionTemplate" ref="sqlSession"/>
</bean>
<bean id="userMapper2" class="com.lhc.dao.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
5.测试
import com.lhc.dao.UserMapper;
import com.lhc.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class mytest {
@Test
public void test() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
12 声明式事务
1 回顾事务
- 把一组业务当成一个业务来做 要么都成功 要么都失败
- 事务在项目开发中 十分重要 设计到数据的一致性问题 不能马虎
- 确保完整性和一致性
事务的ACID原则:
- 原子性
- 一致性
- 隔离性
- 多个事务可能操作同一个资源 防止数据损坏
- 持久性
- 事务一旦提交 无论系统发生什么问题 结果都不会再被影响 被持久化写到存储器中
2 spring中的事务管理
声明式事务
回顾事务
- 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!
- 事务管理是企业级应用程序开发中必备技术,用来确保数据的完整性和一致性。
事务就是把一系列的动作当成一个独立的工作单元,这些动作要么全部完成,要么全部不起作用。
事务四个属性ACID
- 原子性(atomicity)
-
事务是原子性操作,由一系列动作组成,事务的原子性确保动作要么全部完成,要么完全不起作用
-
一致性(consistency)
-
一旦所有事务动作完成,事务就要被提交。数据和资源处于一种满足业务规则的一致性状态中
-
隔离性(isolation)
-
可能多个事务会同时处理相同的数据,因此每个事务都应该与其他事务隔离开来,防止数据损坏
-
持久性(durability)
-
事务一旦完成,无论系统发生什么错误,结果都不会受到影响。通常情况下,事务的结果被写到持久化存储器中
测试
将上面的代码拷贝到一个新项目中
在之前的案例中,我们给userDao接口新增两个方法,删除和增加用户;
//添加一个用户
int addUser(User user);
//根据id删除用户
int deleteUser(int id);
mapper文件,我们故意把 deletes 写错,测试!
<insert id="addUser" parameterType="com.kuang.pojo.User">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<delete id="deleteUser" parameterType="int">
deletes from user where id = #{id}
</delete>
编写接口的实现类,在实现类中,我们去操作一波
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
//增加一些操作
public List<User> selectUser() {
User user = new User(4,"小明","123456");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(4);
return mapper.selectUser();
}
//新增
public int addUser(User user) {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.addUser(user);
}
//删除
public int deleteUser(int id) {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.deleteUser(id);
}
}
测试
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);
}
报错:sql异常,delete写错了
结果 :插入成功!
没有进行事务的管理;我们想让他们都成功才成功,有一个失败,就都失败,我们就应该需要事务!
以前我们都需要自己手动管理事务,十分麻烦!
但是Spring给我们提供了事务管理,我们只需要配置即可;
Spring中的事务管理
Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。
编程式事务管理
- 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
- 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码
声明式事务管理
- 一般情况下比编程式事务好用。
- 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
- 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。
使用Spring管理事务,注意头文件的约束导入 : tx
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
事务管理器
- 无论使用Spring的哪种事务管理策略(编程式或者声明式)事务管理器都是必须的。
- 就是 Spring的核心事务管理抽象,管理封装了一组独立于技术的方法。
JDBC事务
<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="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="search*" propagation="REQUIRED"/>
<tx:method name="get" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
spring事务传播特性:
事务传播行为就是多个事务方法相互调用时,事务如何在这些方法间传播。spring支持7种事务传播行为:
- propagation_requierd:如果当前没有事务,就新建一个事务,如果已存在一个事务中,加入到这个事务中,这是最常见的选择。
- propagation_supports:支持当前事务,如果没有当前事务,就以非事务方法执行。
- propagation_mandatory:使用当前事务,如果没有当前事务,就抛出异常。
- propagation_required_new:新建事务,如果当前存在事务,把当前事务挂起。
- propagation_not_supported:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
- propagation_never:以非事务方式执行操作,如果当前事务存在则抛出异常。
- propagation_nested:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行与propagation_required类似的操作
Spring 默认的事务传播行为是 PROPAGATION_REQUIRED,它适合于绝大多数的情况。
假设 ServiveX#methodX() 都工作在事务环境下(即都被 Spring 事务增强了),假设程序中存在如下的调用链:Service1#method1()->Service2#method2()->Service3#method3(),那么这 3 个服务类的 3 个方法通过 Spring 的事务传播机制都工作在同一个事务中。
就好比,我们刚才的几个方法存在调用,所以会被放在一组事务当中!
配置AOP
导入aop的头文件!
<!--配置aop织入事务-->
<aop:config>
<aop:pointcut id="txPointcut" expression="execution(* com.kuang.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
进行测试
删掉刚才插入的数据,再次测试!
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);
}
思考问题?
为什么需要配置事务?
- 如果不配置,就需要我们手动提交控制事务;
- 事务在项目开发过程非常重要,涉及到数据的一致性的问题,不容马虎!