文章目录
开启自动织入支持
在XML中开启
添aop标签
<aop:aspectj-autoproxy />
开启注解支持,同时强制指定代理机制为cglib
<aop:aspectj-autoproxy proxy-target-class="true" />
通过注解开启
@Configuration
// 开启注解支持,同时强制指定代理机制为cglib
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class MyAOPConf {}
@Component
@Aspect //表示这是一个切面类,里面的方法都是像打印日志等围绕业务方法的方法
注解方式入口类
@Configuration //相当生成一个XML文件
@ComponentScan(basePackages = "com.lanou3g.spring.simple.say")//扫描路径
@EnableAspectJAutoProxy //开启对AOP相关注解的处理
public class AppByAnnotation {
...
}
注解方式定义切面类
@Pointcut:切入点的注解
由于@Aspect注解没有让Spring作为组件bean扫描的能力,所以我们需要额外添加@Component注解
@Aspect // 表示该类是一个切面
@Component // Aspect切面首先必须也是一个普通的bean
public class MethodInOutAspect {
}
Spring的注解的AOP的通知类型
环绕通知@Around
指定该方法是一个环绕通知,通知注解的参数代表引用一个切入点表达式
@Around("com.lanou3g.spring.GlobalPointcut.say_all_method()")
public Object aroundM(ProceedingJoinPoint joinPoint) throws Throwable {}
// 获取连接点方法的名称
String methodName = joinPoint.getSignature().getName();
// 获取连接点方法的参数
Object[] args = joinPoint.getArgs();
@Before:前置通知
@Before("com.lanou3g.spring.GlobalPointcut.say_all_method()")
@AfterReturning:后置通知
@AfterReturning(pointcut = "com.lanou3g.spring.GlobalPointcut.say_all_method()", returning = "ret")
@AfterThrowing:异常抛出通知
@AfterThrowing(value="execution(* "com.lanou3g.spring.GlobalPointcut.say_all_method()" , throwing="e")
@After:最终通知
@After("com.lanou3g.spring.GlobalPointcut.say_all_method()")
方法名 | 功能 |
---|---|
Signature getSignature(); | 获取封装了署名信息的对象,在该对象中可以获取到目标方法名,所属类的Class等信息 |
Object[] getArgs(); | 获取传入目标方法的参数对象 |
Object getTarget(); | 获取被代理的对象 |
Object getThis(); | 获取代理对象 |
Object proceed() throws Throwable | 执行目标方法 |
Object proceed(Object[] var1) throws Throwable | 传入的新的参数去执行目标方法 |
通过@Pointcut注解定义切入点表达式
拦截com.lanou3g.spring.simple.say包下所有类(包括子包中所有类)中的所有方法
@Pointcut(“execution(* com.lanou3g.spring.simple.say….(…))”)
public void say_all_method() {}