1. AOP术语
-
连接点:类里面哪些方法可以被增强,这些方法称为连接点
-
切入点:实际被真正增强的方法,称为切入点
-
通知(增强):实际增强的逻辑部分称为通知(增强)
- 前置通知
- 后置通知
- 环绕通知
- 异常通知
- 最终通知
-
切面:把通知应用到切入点的过程
2. 注解方式
-
被增强类
@Component public class User { public void sayHello(){ System.out.println("hello"); } }
-
增强代理类
@Component @Aspect public class UserProxy { @After("execution(* com.yang.aop.User.sayHello(..))") public void before(){ System.out.println("world!"); } }
@Aspect
注解表示这是一个增强代理类@After("execution(* com.yang.aop.User.sayHello(..))")
表示增强哪一个方法 -
配置文件中扫描代理类
<?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 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:component-scan base-package="com.yang.aop"/> <aop:aspectj-autoproxy/> </beans>
-
不同的增强类型
- @Before
- @After
- @Around
- @AfterReturning
- @AfterThrowing
补充:
@Pointcut
注解可以进行相同切入点提取;- 有多个增强类对同一个方法进行增强,可以在类上添加@Order(value)注解,value越小优先级越高
3. 配置文件方式
<bean id="user" class="com.yang.aop.User"/>
<bean id="userProxy" class="com.yang.aop.UserProxy"/>
<aop:config>
<aop:pointcut id="p" expression="execution(* com.yang.aop.User.sayHello(..))"/>
<aop:aspect ref="userProxy">
<aop:after method="before" pointcut-ref="p"/>
</aop:aspect>
</aop:config>