快速入门
- 创建目标接口和目标类(内部有切点)
- 创建切面类(内部有增强方法)
- 将目标类和切面类的对象创建权交给spring
- 在切面类中使用注解配置织入关系
- 在配置文件中开启组件扫描和AOP的自动代理
- 测试代码
applicationContext-anno.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: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="com.example.anno"/>
<!-- aop自动代理 -->
<aop:aspectj-autoproxy/>
</beans>
注解配置AOP详解
注解通知的类型
通知的配置与法: @通知注解(“切点表达式”)
切点表达时的抽取
切面类MyAspect:
@Component("myAspect")
@Aspect //标注当前MyAspect是一个切面类
public class MyAspect {
...
//ProceedingJoinPoint:正在执行的连接点===切点
//@Around("execution(* com.example.anno.*.*(..))")
@Around("pointcut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前增强......");
Object proceed = pjp.proceed();//切点方法
System.out.println("环绕后增强......");
return proceed;
}
//@After("execution(* com.example.anno.*.*(..))")
@After("MyAspect.pointcut()")
public void after() {
System.out.println("最终增强。。。。");
}
//定义切点表达式
@Pointcut("execution(* com.example.anno.*.*(..))")
public void pointcut(){}
}