首页  

Spring AOP @Aspect     所属分类 spring 浏览量 423
@Aspect 声明切面  与@Component注解一起用使用 交给spring容器管理
切面里声明 Pointcut  和 advice (@Around @Before @AfterReturning 等)
@Pointcut 切点定义  两种方式  annotation  execution

@Component 
@Aspect  @Pointcut @Around @Before @After @AfterThrowing @AfterReturning

@EnableAspectJAutoProxy(proxyTargetClass=false)
proxyTargetClass 可设置成 TRUE ,强制使用 cglib 代理 ,不使用基于接口的 jdk 代理 
使用 cglib 代码 ,可避免 类型转换错误



import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component public class HelloAspect { // LogTag 注解用在方法或接口上无效 @Pointcut("@annotation(LogTag) || execution(* aspect.Hello.*(..))") // @Pointcut("@annotation(LogTag)") // @Pointcut("execution(* aspect.Hello.*(..))") // @Pointcut("@annotation(aspect.LogTag)") private void log() {} @Before("log()") public void doBefore(JoinPoint joinPoint) { System.out.println("doBefore run,joinPoint="+joinPoint); } @Around("log()") public void around(ProceedingJoinPoint joinPoint) { try { System.out.println(joinPoint.getSignature()+" run"); joinPoint.proceed(); } catch (Throwable t) { System.out.println(t); } } }
JoinPoint 获取被代理对象 方法信息 请求参数信息 filter interceptor AOP的区别 filter 一般用于 servlet interceptor (spring),拦截的对象是URL AOP 作用的对象可以是任何一个方法
任意公共方法 execution(public * *(..)) 以 set 开始的方法 execution(* set*(..)) XxxService(类) 任意方法 execution(* a.b.XxxService.*(..)) a.b 包中定义的任意方法 execution(* a.b.*.*(..)) a.b 包及其子包中的任意方法 execution(* a.b..*.*(..))
例子代码 https://gitee.com/dyyx/hellocode/tree/master/demo/springbootdemo/src/main/java/aop https://gitee.com/dyyx/hellocode/tree/master/demo/springbootdemo/src/main/java/aspect
代理的几种实现方式 基于Aspect注解的spring aop 实例 AOP要点整理 AspectJ简介及实例 spring aop 内部方法调用拦截说明 spring aop cglib 代理类源码查看 Spring ProxyFactory 和 方法拦截器 MethodInterceptor

上一篇     下一篇
Dubbo2.7三大新特性简介

zookeeper单机安装

Spring ProxyFactory 和 方法拦截器 MethodInterceptor

powermock 静态方法mock

mockito 实例

Mocktio 指南