Spring实战学习03之--------AOP(面向切片)
一、AOP的简介
1.1 什么是AOP
AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP 是 OOP 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
1.2 AOP的作用和优势
-
作用:在程序 运行期间,在不修改源码的情况下对方法进行功能增强
-
优势:减少重复代码,提高开发效率,并且便于维护
1.3 AOP 的底层实现
实际上,AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。
1.4 AOP 的动态代理技术
常用的动态代理技术
-
JDK 代理 : 基于接口的动态代理技术(缺点:目标对象必须有接口)
-
cglib 代理:基于父类的动态代理技术(不需要接口,基于父类)
1.4.1基于JDK 动态代理的AOP
有不理解什么是动态代理的可以去看一下这篇文章:
设计模式之代理模式
下面我们通过代码来了解JDK的动态代理
要实现动态代理,需要至少需要有三角色:
公共接口,目标对象(被代理对象),代理对象。在这儿我们增加了一个带增强方法的对象
代码实现
1、公共接口(TargetInterface )
public interface TargetInterface {
public void save();
}
2、目标对象/被代理类
/**
* @author 朱霸霸
* @date 2022/6/4 11:07
*/
public class Target implements TargetInterface {
@Override
public void save() {
System.out.println("save running...");
}
}
3、带增强方法的对象(Advice )
public class Advice {
public void before(){
System.out.println("前置增强...");
}
public void afterReturning(){
System.out.println("后置增强...");
}
}
4、代理类测试
public class ProxyTest {
public static void main(String[] args) {
//创建目标对象
final Target target = new Target();
//创建增强对象
Advice advice = new Advice();
//返回值就是动态生成的动态代理对象
TargetInterface proxy=(TargetInterface) Proxy.newProxyInstance(
target.getClass().getClassLoader(),//目标对象的类加载器
target.getClass().getInterfaces(),//目标对象相同的接口字节码对象数组
new InvocationHandler() {
//调用代理对象的任何方法,实质执行的都是invoke方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
advice.before();//前置增强
Object invoke = method.invoke(target, args);//执行目标方法
advice.afterReturning();//后置增强
return invoke;
}
}
);
//调用代理对象的方法
proxy.save();
}
}
测试结果:
1.4.1基于cglib的动态代理
1、导入cglib坐标,由于Spring后期集成了cglib,所以我们只需导入下面的Spring
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
2、代码实现(cglib不需要接口)
2.1 创建目标类
public class Target {
public void save() {
System.out.println("save running...");
}
}
2.2 创建带增强方法的对象
public class Advice {
public void before(){
System.out.println("前置增强...");
}
public void afterReturning(){
System.out.println("后置增强...");
}
}
public class ProxyTest {
public static void main(String[] args) {
//创建目标对象
final Target target = new Target();
//创建增强对象
Advice advice = new Advice();
//返回值 就是动态生成的代理对象 基于cglib
/**
* 1、创建增强器,cglib提供
* 2、设置父类(目标)
* 3、设置回调
* 4、创建代理对象
* 5、测试
*/
//1、创建增强器,cglib提供
Enhancer enhancer = new Enhancer();
//2、设置父类(目标)
enhancer.setSuperclass(Target.class);
//3、设置回调,MethodInterceptor是Callback的子接口
enhancer.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//执行前置
advice.before();
//执行目标
Object invoke = method.invoke(target, args);
//执行后置
advice.afterReturning();
return invoke;
}
});
//4、通过增强器创建代理对象,因为是基于父类的,所以可以使用Target来接收
Target proxy = (Target) enhancer.create();
//调用方法
proxy.save();
}
}
测试结果:
1.5 AOP 核心内容
Spring的AOP实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置文件的方式完成目标的方法增强
1.5.1 AOP的相关概念
-
Target(目标对象):代理的目标对象(
被代理对象
) -
Proxy(代理):一个类被AOP植入增强后,就产生了一个结果代理类
-
Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法(可以被增强的方法),因为spring只支持方法类型的连接点
-
Pointcut(切入点):所谓切入点指的是我们要对那些Jionpoint进行拦截的定义
-
Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知
-
Aspect(切面):是切入点和通知(引介)的结合(切点+通知)
-
Weaving(织入):是指把能增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而Aspect采用编译期织入和类加载期织入(
就是将切点和增强结合的过程
)
1.5.2 AOP开发事项
1、需要编写的内容
-
编写核心业务代码(目标类的目标方法)
-
编写切面类,切面类中有通知(增强功能方法)
-
在配置文件中,配置织入关系,即将哪些通知与哪些连接点进行结合
2、AOP 技术实现的内容
Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建切点方法所在目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
3、AOP 底层使用哪种代理方式(JDK Or Cglib)
在 spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
1.5.3 知识摘要
-
aop:面向切面编程
-
aop底层实现:基于JDK的动态代理 和 基于Cglib的动态代理
-
aop的重点概念:
- Pointcut(切入点):被增强的方法
- Advice(通知/ 增强):封装增强业务逻辑的方法
- Aspect(切面):切点+通知
- Weaving(织入):将切点与通知结合的过程
-
开发明确事项:
- 谁是切点(切点表达式配置
- 谁是通知(切面类中的增强方法)
- 将切点和通知进行织入配置
二、 AOP 的实践应用(配置文件)
开发步骤
①导入 AOP 相关坐标
②创建目标接口和目标类(内部有切点)
③创建切面类(内部有增强方法)
④将目标类和切面类的对象创建权交给 spring(⭐️)
⑤在 applicationContext.xml 中配置织入关系
⑥测试代码
1、导入 AOP 相关坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
2、创建目标接口和目标类(内部有切点)
目标接口:
public interface TargetInterface {
public void save();
}
目标类
public class Target implements TargetInterface {
@Override
public void save() {
System.out.println("save running...");
}
}
3、创建切面类(内部有增强方法)
public class MyAspect {
//增强方法
public void before(){
System.out.println("前置增强");
}
}
4、将目标类和切面类的对象创建权交给 spring(⭐️)
在配置文件中:1、配置目标对象2、配置切面对象
<!--配置目标对象-->
<bean id="target" class="Z.P.aop.Target"></bean>
<!--配置切面对象-->
<bean id="myAspect" class="Z.P.aop.MyAspect"></bean>
5、在 applicationContext.xml 中配置织入关系
在xml中告诉Spring哪些是目标方法(切点)是需要被增强的,增强方法是哪一种
<!--配置织入:告诉spring框架,哪些方法(切点)需要哪些增强(前置、后置、、、)-->
<!--首先要引入aop命名空间
xmlns:aop="http://www.springframework.org/schema/aop"
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
-->
<aop:config>
<aop:aspect ref="myAspect"><!--指定切面类-->
<!--切面:切点+通知-->
<aop:before method="before" pointcut="execution(public void Z.P.aop.Target.save())"/><!--访问save方法时,对该方法进行before()方法增强,增强的方式为前置增强,before()方法在myAspect内封装着-->
</aop:aspect>
</aop:config>
6、测试:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
在这里我们先把增强配置注释掉:
<!-- <aop:config>-->
<!-- <aop:aspect ref="myAspect"><!–指定切面类–>-->
<!-- <!–切面:切点+通知–>-->
<!-- <aop:before method="before" pointcut="execution(public void Z.P.aop.Target.save())"/><!–访问save方法时,对该方法进行before()方法增强,增强的方式为前置增强,before()方法在myAspect内封装着–>-->
<!-- </aop:aspect>-->
<!-- </aop:config>-->
未配置增强的测试结果:
已配置增强的测试结果:
可以看出,都能够运行并能实现目标方法。并且通过aop可以实现解耦合。
切点表达式的写法
表达式语法:
execution([修饰符] 返回值类型 包名.类名.方法名(参数...))
- 访问修饰符可以省略
- 返回值类型、包名、类名、方法名可以使用 * 代表任意
- 包名与类名之间一个点.代表当前包下的类,两个点…代表当前包及其子包下的类
- 参数类表可以使用两个点…表示任意参数,任意类型的参数列表
eg:
execution(public void z.s.aop.Target.method())
execution(void z.s.aop.Target.*(..))
execution(* z.s.aop.*.*(..))
execution(* z.s.aop..*.*(..))
execution(* *..*.*(..))
通知类型
通知配置的语法
<aop:通知类型 method=“切面类中方法名” pointcut=“切点表达式"></aop:通知类型>
切点表达式的抽取
当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用 pointcut-ref 属性代替 pointcut 属性来引用抽取后的切点表达式。
<aop:config>
<!--引用myAspect的Bean为切面对象-->
<aop:aspect ref="myAspect">
<aop:pointcut id="myPointcut" expression="execution(* com.itheima.aop.*.*(..))"/>
<aop:before method="before" pointcut-ref="myPointcut"></aop:before>
</aop:aspect>
</aop:config>
小结
aop织入的配置
<aop:config>
<aop:aspect ref=“切面类”>
<aop:before method=“通知方法名称” pointcut=“切点表达式"></aop:before>
</aop:aspect>
</aop:config>
- 通知的类型:前置通知、后置通知、环绕通知、异常抛出通知、最终通知
- 切点表达式的写法:
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
三、 AOP 的实践应用(注解开发)
3.1 基于注解的开发步骤
①创建目标接口和目标类(内部有切点)
②创建切面类(内部有增强方法)
③将目标类和切面类的对象创建权交给 spring
④在切面类中使用注解配置织入关系
⑤在配置文件中开启组件扫描和 AOP 的自动代理
⑥测试
代码实现:
1、创建目标接口和目标类(内部有切点)
目标接口:
public interface TargetInterface {
public void save();
}
目标类
public class Target implements TargetInterface {
@Override
public void save() {
System.out.println("save running...");
}
}
2、创建切面类(内部有增强方法)
public class MyAspect {
//增强方法
public void before(){
System.out.println("前置增强");
}
}
3、将目标类和切面类的对象创建权交给 spring
@Component("myAspect")
public class MyAspect {...}
@Component("target")
public class Target implements TargetInterface {...}
4、在切面类中使用注解配置织入关系
@Component("myAspect")
@Aspect //标注当前MyAspect是一个切面类
public class MyAspect {
//配置前置增强
@Before("execution(* Z.P.anno.*.*(..))")
public void before(){
System.out.println();
}
public void afterReturning(){
System.out.println("后置增强...");
}
public Object around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("环绕前置增强...");
Object proceed = pjp.proceed(); //切点方法
return proceed;
}
}
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: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="Z.P.anno"/>
</beans>
6、测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AopTest {
@Autowired
private TargetInterface target;
@Test
public void test1(){
target.save();
}
}
3.2 注解配置AOP详解
1、注解通知的类型
通知的配置语法:
@通知注解(“切点表达式")
2、切点表达式的抽取
同 xml配置
aop 一样,我们可以将切点表达式抽取。抽取方式是在切面内定义方法,在该方法上使用@Pointcut注解定义切点表达式,然后在在增强注解中进行引用。具体如下:
@@Component("myAspect")
@Aspect
public class MyAspect {
@Before("MyAspect.myPoint()")
public void before(){
System.out.println("前置代码增强.....");
}
@Pointcut("execution(* com.itheima.aop.*.*(..))")
public void myPoint(){}
}