AOP
概述
1、面向切面编程:Aspect Oriented Programming
2、不修改源代码情况下,添加功能
3、对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率
底层原理
1、使用动态代理
(1)有接口情况下,使用 JDK 动态代理,创建接口的实现类代理对象
(2)没有接口情况下,使用 CGLIB 动态代理,创建当前类的子类代理对象
2、JDK 动态代理
(1)java.lang.reflect.Proxy 类
(2)返回指定接口的代理类的实例,该接口将方法调用分派给指定的调用处理程序
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
/*
loader:类加载器
interfaces:增强方法所在的类,这个类实现的接口,支持多个接口
h:实现这个接口InvocationHandler,创建代理对象,与增强部分
*/
(3)代码示例
//创建接口,定义方法
interface ProxyInterface {
public void print(String string);
}
//创建接口实现类,实现方法
class Target implements ProxyInterface {
@Override
public void print(String string) {
System.out.println("实现print方法");
}
}
class ProxyFactory {//代理工厂类
private Object target;//目标对象
public ProxyFactory(Object target) {
this.target = target;
}
//给目标对象生成代理对象
public Object getProxyInstance() {
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("在print方法之前增强");
//反射机制调用目标对象的方法
Object returnValue = method.invoke(target, args);
System.out.println("在print方法之后增强");
//返回目标对象方法的返回值
return returnValue;
}
});
}
}
操作术语
1、连接点:类中可以被增强的方法
2、切入点:类中实际被增强的方法
3、通知 / 增强:实际增强的逻辑部分
(1)前置通知:在连接点前面执行,前置通知不会影响连接点的执行,除非此处抛出异常
(2)返回通知:在连接点正常执行完成后执行,如果连接点抛出异常,则不会执行
(3)环绕通知:在目标方法执行之前和之后都可以执行额外代码的通知,在环绕通知中必须显式的调用目标方法,目标方法才会执行,这个显式调用时通过 ProceedingJoinPoint 实现
(4)异常通知:在连接点抛出异常后执行
(5)最终通知 / 后置通知:在连接点执行完成后执行,不管是正常执行完成,还是抛出异常,都会执行返回通知中的内容
4、切面:把通知应用到切入点的过程
AOP 操作前置
1、Spring 框架一般都是基于 AspectJ 实现 AOP 操作
2、AspectJ:不是 Spring 组成部分,而是独立 AOP 框架,一般把 AspectJ 和 Spring 框架一起使用,进行 AOP 操作
3、基于 AspectJ 实现 AOP 操作
(1)基于 xml 配置文件
(2)基于注解方式:实际开发时使用
4、项目工程引入 AOP 相关依赖
(1)spring-aop:包含在应用中使用 Spring 的 AOP 特性时,所需的类和源码级元数据支持
(2)spring-aspect:提供对 AspectJ 的支持,可以将面向方面的功能集成进 IDE 中
(3)cglib:为没有实现接口的类提供代理,为 JDK 的动态代理提供了很好的补充,通常可以使用 Java 的动态代理创建代理
(4)aopalliance:Java 中对于面向切面提供了一系列标准化接口
(5)aspectjweaver:用于实现 AOP 切入点表达式、AOP 相关注解
5、切入点表达式
(1)作用:指定被增强的方法
(2)语法结构:execution(访问修饰符 返回值类型 全类名.方法名(形参列表))
(3)访问修饰符可以省略
(4)返回值使用 *,表示任意返回值
(5)包名使用 *,表示任意包,有 n 级包,写 n 个 *,包名可以使用 .. ,表示当前包及其子包
(6)类名可以使用 *,表示任意类
(7)方法名可以使用 *,表示任意方法
(8)形参列表:写入参数类型,用逗号分隔,() 匹配一个无参方法,(..) 匹配一个可接受任意数量参数和类型的方法,(*) 匹配一个接受一个任意类型参数的方法
(9)全通配:* *..*.*(..)
6、通知注解
(1)@Before:前置通知
(2)@Around:环绕通知
(3)@AfterRunning:返回通知
(4)@After:最终通知 / 后置通知
(5)@AfterThrowing:异常通知
基于 AspectJ 注解操作(实际开发时使用)
1、创建普通类,定义方法;创建增强类,创建不同方法,代表不同类型通知
(1)配置不同类型通知:增强类中,在作为通知方法上,添加通知类型注解,使用切入点表达式配置
(2)使用注解创建普通类、增强类的对象
(3)在增强类上,添加注解 @Aspect
//目标类
@Component
class Target {
public void normal() {
System.out.println("普通方法");
}
}
//增强类
@Component
@Aspect
class Proxy {
//前置通知
@Before(value = "execution(* *..Target.normal())")
public void before() {
System.out.println("前置通知");
}
//后置通知 / 最终通知
@After(value = "execution(* *..Target.normal(..))")
public void after() {
System.out.println("后置通知");
}
//异常通知
@AfterThrowing(value = "execution(* *..Target.normal(..))")
public void afterThrowing() {
System.out.println("异常通知");
}
//环绕通知
@Around(value = "execution(* *..Target.normal(..))")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕之前");
proceedingJoinPoint.proceed();
System.out.println("环绕之后");
}
//返回通知
@AfterReturning(value = "execution(* *..Target.normal(..))")
public void afterRunning() {
System.out.println("返回通知");
}
}
2、xml 配置
(1)在 Spring 配置文件中,开启注解扫描
(2)在 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"
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="包路径"></context:component-scan>
<!-- 开启Aspect生成代理对象 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
3、配置类,使用注解配置
(1)@Configuration:表示配置类
(2)@ComponentScan(basePackages = {"包路径"}):开启组件扫描
(3)@EnableAspectJAutoProxy(proxyTargetClass = true):开启 Aspect 生成代理对象,proxyTargetClass 默认 false
@Configuration
@ComponentScan(basePackages = {"包路径"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAOP {
}
4、抽取公共切入点
//增强类
@Component
@Aspect
class Proxy {
//相同切入点抽取
@Pointcut(value = "refine()")
public void refine(){
}
//前置通知
@Before(value = "refine()")
public void before() {
System.out.println("前置通知");
}
//后置通知 / 最终通知
@After(value = "refine()")
public void after() {
System.out.println("后置通知");
}
//异常通知
@AfterThrowing(value = "refine()")
public void afterThrowing() {
System.out.println("异常通知");
}
//环绕通知
@Around(value = "refine()")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕之前");
proceedingJoinPoint.proceed();
System.out.println("环绕之后");
}
//返回通知
@AfterReturning(value = "refine()")
public void afterRunning() {
System.out.println("返回通知");
}
}
4、多个增强类对同一方法增强
(1)设置增强优先级
(2)在增强类上,添加注解 @Order(数字类型值)
(3)数字类型值越小优先级越高
(4)不标注数字,默认最低优先级,其默认值是 int 最大值
//增强类1
@Component
@Aspect
@Order(1)
class Proxy1 {
//前置通知1
@Before(value = "execution(* *..Target.normal())")
public void before() {
System.out.println("前置通知1");
}
}
//增强类2
@Component
@Aspect
@Order(2)
class Proxy {
//前置通知2
@Before(value = "execution(* *..Target.normal)")
public void before() {
System.out.println("前置通知2");
}
}
基于 AspectJ 配置文件操作
1、创建两个类:增强类、被增强类,并创建方法
//目标类
class Target {
public void normal() {
System.out.println("普通方法");
}
}
//增强类
class Proxy {
//前置通知
public void before() {
System.out.println("前置通知");
}
}
2、在 Spring 配置文件中创建两个类对象
3、在 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: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 id="target" class="Target"></bean>
<bean id="proxy" class="Proxy"></bean>
<!-- 配置AOP增强 -->
<aop:config>
<!--切入点:id:切入点名称;expression:切入点表达式-->
<aop:pointcut id="targetPointcut" expression="execution(* *..Target.normal(..))"/>
<!-- 配置切面 -->
<aop:aspect ref="proxy">
<!-- 通知类型;method:增强方法名;pointcut-ref:被增强方法id值 -->
<aop:before method="before" pointcut-ref="targetPointcut"></aop:before>
</aop:aspect>
</aop:config>
</beans>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战