Spring学习笔记
Spring
Spring
简介
- Spring--->给软件行业带来了春天。
- 2002年,首次推出了Spring的雏形,interface21框架。
- Spring以interface21框架为基础,经过重新设计,不断丰富,于2004年3月24号发布了1.0正式版。
- 目的:解决企业应用开发的复杂性,使现有的技术更容易使用。
官方下载地址:https://repo.spring.io/release/org/springframework/spring
GitHub:https://github.com/spring-projects/spring-framework
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
优点
- Spring是一个开源的免费框架(容器)。
- Spring是一个轻量级的,非入侵式的框架。
- 控制反转(IOC),面向切面(AOP)。
- 支持事务的处理,对框架整合的支持。
Spring是一个轻量级的,控制反转(IOC),面向切面(AOP)的框架。
组成

IOC理论推导
-
UserDao接口
public interface UserDao { void getUser(); } -
UserDaoImpl实现类
public class UserDaoImpl implements UserDao{ public void getUser() { System.out.println("默认获取用户的数据!"); } }public class UserDaoMysqlImpl implements UserDao{ public void getUser() { System.out.println("Mysql获取数据!"); } } -
UserService业务接口
public interface UserService { void getUser(); } -
UserServiceImpl业务实现类
public class UserServiceImpl implements UserService{ //原来的方法 这里的方法写死了 //private UserDao userDao = new UserDaoImpl(); //调用UserDaoMysqlImpl的实现类 //private UserDao userDao = new UserDaoMysqlImpl(); private UserDao userDao; //利用set方法实现动态的注入 public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void getUser() { userDao.getUser(); } } -
测试
public class MyTest { public static void main(String[] args) { //用户实际调用的是业务层 原来的方法 //UserServiceImpl userService = new UserServiceImpl(); // userService.getUser(); //用户实际调用的是业务层 UserServiceImpl userService = new UserServiceImpl(); //接收UserDaoMysqlImpl的实现 userService.setUserDao(new UserDaoMysqlImpl()); userService.getUser(); } }
在之前的业务中,如果不使用set注入,用户的需可能影响我们原来的代码,比如,用户想要调用UserDaoMysqlImpl,我们需要根据用户的需求去改变我们原来的代码!修改的成本十分昂贵。
使用set接口实现:
private UserDao userDao;
//利用set实现动态的注入
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
之前,程序主动创建对象,控制权在程序员手上。
使用set注入后,程序不在具有主动性,变成被动地接收对象。
这种思想,从本质上解决了问题,我们不用再去管理对象的创建了,系统的耦合性大大降低,可以更加专注在业务的实现上。这是IOC的原型!
IOC本质
控制反转(IOC)是一种思想,DI(依赖注入)是实现IOC的一种方式。
Ioc是Spring框架的核心,实现Ioc,可以使用XML配置,也可以使用注解,新版本的Spring可以零配置实现Ioc。
Spring容器在初始化时先读取配置文件,根据配置文件或原数组创建与组织对象存入容器中,程序使用时从Ioc容器中取出需要的对象。
使用XML方式配置Bean的时候,Bean的定义信息和实现是分离的,而采用注解的方式可以把两者和为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式,在Spring中实现控制反转的是Ioc容器,其实现方式是依赖注入。
HelloSpring
实体类
package com.zr.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
applications.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring来创建对象,在Spring中这些称为Bean
类型 变量名 = new 类型
Hello hello = new Hello()
id = 变量名
class = 要new的对象
property相当于给对象中的属性设置值
-->
<bean id="hello" class="com.zr.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
测试
public class MyTest {
public static void main(String[] args) {
//获取Spring的上下文对象
ApplicationContext context = new ClassPathXmlApplicationContext("applications.xml");
//我们的对象都在Spring容器中了,我们要使用,直接去里面取就可以
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
IOC推导案例UserServiceImpl修改为XML配置
applications.xml中添加
<bean id="mysqlImpl" class="com.zr.dao.UserDaoMysqlImpl"/>
<bean id="impl" class="com.zr.dao.UserDaoImpl"/>
<bean id="UserServiceImpl" class="com.zr.service.UserServiceImpl">
<!-- ref引用Spring容器中创建好的对象
value :具体的值 基本数据类型
-->
<property name="userDao" ref="mysqlImpl"/>
</bean>
测试
public class MyTest {
public static void main(String[] args) {
//xml配置文件 获取ApplicationContext 拿到Spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("applications.xml");
//需要什么直接拿
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}
现在,我们彻底不需要取修改代码了,要实现不同的操作,只需要在XML配置文件中进行修改。对象由Spring来创建,管理,装配。
IOC创建对象的方式
-
使用无参构造创建对象,默认!
-
假设我们要使用有参构造创建方法 。
1.下标赋值
<!--下标赋值--> <bean id="user" class="com.zr.pojo.User"> <constructor-arg index="0" value="周周"/> </bean>2.类型赋值
<!--通过类型创建,不建议使用--> <bean id="user" class="com.zr.pojo.User"> <constructor-arg type="java.lang.String" value="小周"/> </bean>3.通过参数名设置
<!--直接通过参数名设置--> <bean id="user" class="com.zr.pojo.User"> <constructor-arg name="name" value="周周周"/> </bean>
在配置文件加载的时候,容器中管理的对象就已经初始化了!
Spring配置
别名
<!-- 别名-->
<alias name="user" alias="newname"/>
Bean的配置
<!--
id:bean的唯一标识符 相当于对象名
class:bean对象所对应的全限定名:包名+类名
name:起别名,可以同时取多个名字,可以用逗号,空格,分号分隔
-->
<bean id="user" class="com.zr.pojo.User" name="newuser,newuser2">
<property name="name" value="周"/>
</bean>
Import
一般团队开发使用,可以将多个配置文件,导入合并为一个。
假设项目中有多个人开发,每个人负责不同类的开发,不同的类注册在不同的bean中,我们就可以使用import将它们合并。
<import resource="bean.xml"/>
<import resource="bean2.xml"/>
使用的时候直接使用总的配置就可以了。
依赖注入(DI)
构造器注入
有参构造方法注入。
set方式注入【重点】
- 依赖:bean对象的创建依赖于容器。
- 注入:bean对象中的所有属性,由容器注入。
【测试环境搭建】
-
复杂类型
public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Address{" + "address='" + address + '\'' + '}'; } } -
真实测试对象
public class Student { private String name; private Address address; private String[] books; private List<String> hobby; private Map<String,String> card; private Set<String> game; private String wife; private Properties info; //添加get,set,toString方法 } -
applictions.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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.zr.pojo.Address"> <property name="address" value="武汉"/> </bean> <bean id="student" class="com.zr.pojo.Student"> <!-- 普通值注入:value--> <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="hobby"> <list> <value>听歌</value> <value>写字</value> <value>敲代码</value> </list> </property> <!-- map--> <property name="card"> <map> <entry key="身份证" value="4223231998"/> <entry key="学号" value="10210416200"/> </map> </property> <!-- set--> <property name="game"> <set> <value>LOL</value> <value>王者</value> <value>吃鸡</value> </set> </property> <!-- null--> <property name="wife"> <null/> </property> <!-- properties--> <property name="info"> <props> <prop key="年龄">20</prop> <prop key="身高">180</prop> </props> </property> </bean> </beans> -
测试类
public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applications.xml"); Student student = (Student) context.getBean("student"); System.out.println(student.toString()); } }
拓展方式注入
可以使用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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入,可以直接注入一些属性的值:property-->
<bean id="user" class="com.zr.pojo.User" p:name="周周" p:age="18"/>
<!--c命名空间注入,通过构造器注入:construct-args(pojo中加有参构造和无参构造)-->
<bean id="user2" class="com.zr.pojo.User" c:_0="20" c:_1="小周"/>
</beans>
测试:
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbean.xml");
User user = context.getBean("user2", User.class);
System.out.println(user);
}
注意:p命名空间和c命名空间需要导入xml约束。
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
Bean的作用域
-
单例模式(默认)每次从容器中get的时候,拿到的都是同一个对象。
<bean id="user2" class="com.zr.pojo.User" c:_0="20" c:_1="小周" scope="singleton"/> -
原型模式,每次从容器中get的时候,都会产生新对象。
<bean id="user2" class="com.zr.pojo.User" c:_0="20" c:_1="小周" scope="prototype"/> -
其余的request,session,application只在web开发中使用。
Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式。
- Spring会在上下文中自动寻找,并自动地给bean装配属性。
在Spring有三种装配的方式:
- 在xml中显式地配置
- 在Java中配置
- 隐式地自动装配bean【重要】
环境搭建:一个人有两个宠物。
public class Dog {
public void shout(){
System.out.println("旺");
}
}
public class Cat {
public void shout(){
System.out.println("喵");
}
}
public class People {
private Cat cat;
private Dog dog;
private String name;
//get,set,toString方法省略,需要自己添加
}
application.xml
<bean id="cat" class="com.zr.pojo.Cat"/>
<bean id="dog" class="com.zr.pojo.Dog"/>
<bean id="people" class="com.zr.pojo.People">
<property name="name" value="周周"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
byName自动装配
<bean id="cat" class="com.zr.pojo.Cat"/>
<bean id="dog" class="com.zr.pojo.Dog"/>
<!-- byName:会自动地在容器上下文查找,和自己对象set方法后面地值对应的bean的id-->
<bean id="people" class="com.zr.pojo.People" autowire="byName">
<property name="name" value="周周"/>
</bean>
byType自动装配
<bean class="com.zr.pojo.Cat"/>
<bean class="com.zr.pojo.Dog"/>
<!-- byName:会自动地在容器上下文查找,和自己对象set方法后面地值对应的bean的id-->
<!-- byType:会自动地在容器上下文查找,和自己对象属性类型相同的bean-->
<bean id="people" class="com.zr.pojo.People" autowire="byType">
<property name="name" value="周周"/>
</bean>
测试
public class MyTest {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
People people = context.getBean("people", People.class);
people.getDog().shout();
people.getCat().shout();
}
}
小结:
- byName,需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致。
- byType,需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致。
使用注解实现自动装配
jdk1.5支持的注解,spring2.5支持的注解。
使用:
-
导入约束,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/> </beans>
@AotoWired:直接在属性上使用即可,也可以在set方法上使用。
在属性上使用@AotoWired可以不用编写set方法了,前提是自动装配的属性在IOC容器中存在。
拓展:
@Nullable //字段标注了这个注解说明这个字段可以为null。
注解自动装配(以下pojo类省略了set,个体,toString,测试必须加上!!!)
public class People {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
<bean id="cat" class="com.zr.pojo.Cat"/>
<bean id="dog" class="com.zr.pojo.Dog"/>
<bean id="people" class="com.zr.pojo.People"/>
测试
public class MyTest {
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
People people = context.getBean("people", People.class);
people.getDog().shout();
people.getCat().shout();
}
}
@Autowired(required = false)(默认不设置required为true)
public class People {
//如果显式定义@Autowired属性为false,说明这个对象可以为null
@Autowired(required = false)
private Cat cat;
@Autowired
@Qualifier(value = "dog")
private Dog dog;
private String name;
}
<bean id="dog" class="com.zr.pojo.Dog"/>
<bean id="people" class="com.zr.pojo.People"/>
如上@Autowired(required = false)时,bean中不注入cat,程序可以运行,会执行people.getDog().shout()方法,但同时会报空指针异常的错误。如果bean中不注入cat类,且@Autowired没有设置为false,程序将无法运行。
@Qualifier(value = "×××")
默认情况下,@Autowired 按类型装配 Spring Bean。如果容器中有多个相同类型的 bean,则框架将抛出 NoUniqueBeanDefinitionException, 以提示有多个满足条件的 bean 进行自动装配,程序无法正确做出判断使用哪一个。
如果 @Autowired自动装配的环境比较复杂,无法使用一个注解【 @Autowired】完成的时候,可以使用@Qualifier(value = "×××")来配合@Autowired,指定一个唯一的bean对象注入。
public class People {
@Autowired
private Cat cat;
@Autowired
@Qualifier(value = "dog")//指定bean的id
private Dog dog;
private String name;
}
@Resource注解
public class People {
@Resource(name = "cat")
private Cat cat;
@Resource(name = "dog")
private Dog dog;
private String name;
}
小结: @Resource和 @Autowired的区别
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired是按类型(byType)装配,必须要求这个对象存在。
- @Resource是默认按名字(byName)装配,如果找不到,再去按类型装配,都找不到时会报错。
使用注解开发
在Spring4之后,要使用注解开发,必须保证aop的包导入了。
使用注解需要导入context约束,和配置注解支持。
@Component:组件,放在类上,说明这个类被Spring管理了,就是一个bean。
//组件 等价于注册了一个bean
@Component
//作用域
@Scope("singleton")
public class User {
public String name;
//相当于<property name="name" value="周周"/>
@Value("周周")
public void setName(String name) {
this.name = name;
}
}
-
@Component有几个衍生的注解,在web开发中,会按照mvc三层架构分层。
-
dao【@Repository】
-
service【@Service】
-
controller【@Controller】
以上四个注解的功能都是一样的,都代表将某个类注册到Spring容器中,装配Bean。
小结:
xml与注解:
- xml更加万能,使用于任何场合,维护简单方便。
- 注解,维护相对复杂。
结合使用,xml用来管理bean,注解用来完成属性的注入。
注意:让注解生效,要开启注解支持,扫描注解包。
<!-- 扫描指定的包,让包下的注解生效-->
<context:component-scan base-package="com.zr"/>
<!-- 注解支持-->
<context:annotation-config/>
使用Java的方式配置Spring
不使用xml配置,使用Java。
JavaConfig是Spring的一个子项目。在Spring4之后,成为了核心功能。
public class User {
private String name;
public String getName() {
return name;
}
@Value("周周周")
public void setName(String name) {
this.name = name;
}
}
Config类
//代表这是一个配置类,相当于bean.xml,注册到Spring容器中,本质就是一个Component
@Configuration
//引入另一个配置文件,相当于bean.xml中<import resource="bean2.xml"/>
@Import(Config2.class)
public class Config {
//注册一个bean,相当于bean标签
//方法名,相当于bean标签中的id属性
//返回值,相当于bean标签中的class属性
@Bean
public User getUser(){
return new User();//返回要注入bean的对象
}
}
测试
public class MyTest {
@Test
public void test1(){
//使用配置类,要通过AnnotationConfig上下文来获取容器,通过配置类的class来加载
ApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
User user = (User) context.getBean("getUser");//取方法名
System.out.println(user.getName());
}
}
这种纯Java的配置方式,在SpringBoot中常用。
代理模式
Spring的底层--->>代理模式!
代理模式分类:
- 静态代理
- 动态代理
静态代理
角色分析:
- 抽象角色:一般使用接口或者抽象类
- 真实角色:被代理(房东)
- 代理角色:代理真实角色,代理真实角色后,一般会做一些其它操作
- 客户:访问代理对象的人
代码实现:
-
接口
//租房 public interface Rent { public void rent(); } -
真实角色
//房东 public class Host implements Rent{ public void rent() { System.out.println("房东要出租"); } } -
代理角色
public class Proxy implements Rent{ private Host host; public Proxy() { } public Proxy(Host host) { this.host = host; } public void rent() { seeHouse(); host.rent(); fare(); } //看房 public void seeHouse(){ System.out.println("中介带你看房"); } //中介费 public void fare(){ System.out.println("中介收中介费"); } } -
客户访问代理角色
public class Client { public static void main(String[] args) { //房东租房子 Host host = new Host(); //代理 中介帮房东租房子,中间会有其它操作 Proxy proxy = new Proxy(host); //通过中介租房 proxy.rent(); } }
代理模式的好处:
- 真实角色不用去关注具体的业务
- 业务交给代理角色,实现了业务的分工
- 业务发生扩展的时候,方便集中管理
确定:一个真实角色就会产生一个代理角色,真实角色多的时候,代码翻倍,开发效率低。
加深理解
接口
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
真实对象
//真实对象
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("查询了一个用户!");
}
}
代理对象
public class UserServiceProxy implements UserService{
private UserServiceImpl userService;
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
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+"方法");
}
}
客户端
public class Client {
public static void main(String[] args) {
UserServiceImpl userService = new UserServiceImpl();
UserServiceProxy proxy = new UserServiceProxy();
proxy.setUserService(userService);
proxy.add();
}
}
动态代理
- 动态代理和静态代理角色一样
- 动态代理的代理类是动态生成的
- 动态代理分为两大类,基于接口的动态代理,基于类的动态代理
- 基于接口:JDK的动态代理
- 基于类:cglib
- java字节码实现:Javasist
需要了解两个类:Proxy:代理,InvocationHandler:调用处理程序
//租房
public interface Rent {
public void rent();
}
//房东
public class Host implements Rent {
public void rent() {
System.out.println("房东要出租");
}
}
动态代理
//自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler{
//被代理的接口
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//得到生成的代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质使用反射实现
seeHouse();
Object result = method.invoke(rent, args);
fare();
return result;
}
public void seeHouse(){
System.out.println("中介带看房子");
}
public void fare(){
System.out.println("中介收中介费");
}
}
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色,现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色来处理我们要调用的接口对象
pih.setRent(host);
//这里的proxy就是动态生成的
Rent proxy = (Rent) pih.getProxy();
proxy.rent();
}
}
加深理解
public interface UserService {
public void add();
public void delete();
public void update();
public void query();
}
//真实对象
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("查询了一个用户!");
}
}
动态代理(不设定代理接口,使用时传入,万能的)
//自动生成代理类
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 +"方法");
}
}
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.add();
}
}
动态代理的好处:
- 真实角色不用去关注具体的业务
- 业务交给代理角色,实现了业务的分工
- 业务发生扩展的时候,方便集中管理
- 一个动态代理类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一接口即可
AOP
Aop:面向切面编程,通过预编译和运行期动态代理实现程序功能的统一维护的一种技术,。AOP是OOP的延续,是软件开发的一个热点,也是Spring中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑各个部分进行隔离,从而使业务逻辑各部分之间的耦合性降低,提高程序的可用性,同时提高了开发的小路。
AOP在Spring中的作用
提供声明式事务,允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能,即,与我们业务逻辑无关,但我们需要关注的部分,就是横切关注点,如日志,安全,缓存,事务等等...
- 切面(Aspect):横切关注点,被模块化的特殊对象,即,它是一个类
- 通知(Advice):切面必须完成的工作,即,它是类中的一个方法
- 目标(Target):被通知的对象
- 代理(Proxy):向目标对象应用通知后创建的对象
- 切入点(PointCut):切面通知,执行的“地点”的定义
- 连接点(joinPoint):与切入点匹配的执行点
Spring实现Aop
pom.xml导入依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
方式一:使用Spring的api接口实现
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
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 select() {
System.out.println("查询了一个用户");
}
}
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象方法
//objects:参数
//o:目标对象
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//Object o:返回值
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了"+method.getName()+"返回的结果为"+o);
}
}
application.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 注册bean-->
<bean id="userService" class="com.zr.service.UserServiceImpl"/>
<bean id="log" class="com.zr.log.Log"/>
<bean id="afterLog" class="com.zr.log.AfterLog"/>
<!--方式一:使用原生Spring api接口-->
<!--配置aop,需要导入aop的约束-->
<aop:config>
<!--切入点 expression:表达式 execution(要执行的位置)-->
<aop:pointcut id="pointcut" expression="execution(* com.zr.service.UserServiceImpl.*(..))"/>
<!--执行环绕增强-->
<aop:advisor advice-ref="log" 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("application.xml");
//动态代理的是接口
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
方式二:自定义实现AOP【切面设定】
public class DiyPointCut {
public void before(){
System.out.println("方法执行前");
}
public void after(){
System.out.println("方法执行后");
}
}
将application.xml方式一替换为:
<!--方式二:自定义类-->
<bean id="diy" class="com.zr.diy.DiyPointCut"/>
<aop:config>
<!--自定义切面 ref要引用的类-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* com.zr.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
方式三:使用注解实现
//使用注解方式实现AOP
@Aspect //标注这是一个切面
public class AnnotationPiontCut {
@Before("execution(* com.zr.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("方法执行前AnnotationPiontCut");
}
@After("execution(* com.zr.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("方法执行后AnnotationPiontCut");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.zr.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
//执行方法
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}
<!--方式三-->
<bean id="annotation" class="com.zr.diy.AnnotationPiontCut"/>
<!--开启注解支持 JDK(默认:proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy/>
以上三种方式测试类一样。
整合Mybatis
回顾
步骤:
-
导入相关jar包
- junit
- mybatis
- mysql数据库
- spring相关
- aop织入
- spring-jdbc
- mybatis-spring
- lembok
-
实体类
@Data public class User { private int id; private String name; private String pwd; } -
接口
public interface UserMapper { public List<User> selectUser(); } -
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zr.mapper.UserMapper"> <select id="selectUser" resultType="User"> select * from user; </select> </mapper> -
编写配置文件mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <package name="com.zr.pojo"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" 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"/> </dataSource> </environment> </environments> <mappers> <mapper class="com.zr.mapper.UserMapper"/> </mappers> </configuration> -
测试
@Test public void test() throws IOException { String resoueces = "mybatis-config.xml"; InputStream in = Resources.getResourceAsStream(resoueces); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in); SqlSession sqlSession = sessionFactory.openSession(true); UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> list = mapper.selectUser(); for (User user : list) { System.out.println(user); } }
mybatis-spring
实体类,UserMapper接口和UserMapper.xml不变
SqlSessionTemplate
-
spring-dao.xml(数据库配置,sqlSessionFactory,sqlSessionTemplate)
<?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 https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--数据源,是用spring的数据源替换mybatis的配置--> <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> <!--sqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!-- 绑定mybatis配置文件--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/zr/mapper/*.xml"/> </bean> <!--SqlSessionTemplate就是我们使用的SqlSession--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--只能使用构造器注入sqlSessionFactory,因为它没有set方法--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> </beans> -
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <package name="com.zr.pojo"/> </typeAliases> </configuration> -
给接口加实现类
public class UserMapperImpl implements UserMapper{ //原来我们的所有操作都使用SqlSession执行,现在都使用SqlSessionTemplate private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } public List<User> selectUser() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser(); } } -
实现类注入到application.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:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <import resource="spring-dao.xml"/> <bean id="userMapper" class="com.zr.mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> </beans> -
测试
@Test public void test2(){ ApplicationContext context = new ClassPathXmlApplicationContext("application.xml"); UserMapper userMapper = context.getBean("userMapper", UserMapper.class); for (User user : userMapper.selectUser()) { System.out.println(user); } }
SqlSessionDaoSupport【了解】
SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法.
实现类
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
public List<User> selectUser() {
//SqlSession sqlSession = getSqlSession();
//UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//return mapper.selectUser();
//简化
return getSqlSession().getMapper(UserMapper.class).selectUser();
}
}
application.xml加入
<bean id="userMapper2" class="com.zr.mapper.UserMapperImpl2">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
测试类将test2的userMapper修改为userMapper2即可。
声明式事务
- 把一组业务当成一个业务来做,要么都成功,要么都失败
- 事务在项目开发中,十分重要,涉及到数据一致性问题
事务的ACID原则:原子性,一致性,隔离性,持久性
Spring中的事务管理
- 声明式事务:AOP
- 编程式事务:需要在代码中进行事物的管理
为什么需要事务:
-
如果不配置事务,可能存在事务不一致的情况
-
如果不在Spring中配置声明式事务,,我们就要在代码中手动配置事务
-
事务在项目开发中十分重要,涉及到数据库的一致性和完整性
代码示例:以下代码中没有开启事务,如果UserMapperImpl中的mapper.delete(7)出现错误(比如将sql语句写错),程序会报错,但是mapper.add(user)方法依然可以执行成功,不能保证数据的一致性!!!
实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
UserMapper
public interface UserMapper {
public List<User> selectUser();
//添加用户
public int add(User user);
//删除用户
public int delete(int id);
}
UserMapperImpl
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
public List<User> selectUser() {
User user = new User(7, "韩信", "99999");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
mapper.add(user);
mapper.delete(7);
return mapper.selectUser();
}
public int add(User user) {
return getSqlSession().getMapper(UserMapper.class).add(user);
}
public int delete(int id) {
return getSqlSession().getMapper(UserMapper.class).delete(id);
}
}
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zr.mapper.UserMapper">
<select id="selectUser" resultType="User">
select * from user;
</select>
<insert id="add" parameterType="user">
insert into user(id,name,pwd) value (#{id},#{name},#{pwd});
</insert>
<delete id="delete" parameterType="int">
delete from user where id = #{id};
</delete>
</mapper>
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.zr.pojo"/>
</typeAliases>
</configuration>
spring-dao.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd">
<!--数据源,是用spring的数据源替换mybatis的配置-->
<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>
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!-- 绑定mybatis配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/zr/mapper/*.xml"/>
</bean>
<!--SqlSessionTemplate就是我们使用的SqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--只能使用构造器注入sqlSessionFactory,因为它没有set方法-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
application.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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml"/>
<bean id="userMapper" class="com.zr.mapper.UserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
测试MyTest
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("application.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
List<User> users = userMapper.selectUser();
for (User user : users) {
System.out.println(user);
}
}
}
添加事务的支持
现在我们在spring-dao.xml中添加以下代码,开启事务,这样当mapper.delete(7)发生错误时,同一业务中的其它操作也不会执行成功,保证事务的一致性。
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<constructor-arg ref="dataSource"/>
</bean>
<!--结合AOP,实现事物的织入-->
<!--配置事物通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给哪些方法配置事务 配置事务事务传播特性(可以不写 ,默认required)-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<!-- 所有方法-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.zr.mapper.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
测试,可以看到将delete方法发生错误时(制造错误:将sql语句写错),add方法也没有执行成功,要么都成功,要么都失败。

浙公网安备 33010602011771号