摘要
- aop关键词
- spring aop小demo
<!--more-->
概念
应用场景:与业务无关的且常常应用到的公共性能如鉴权,日志,性能优化,事务,错误处理,资源池,同步,审计,幂等等长处:升高耦合度,易扩大,高复用
实现形式:动态代理(AspectJ) + 动静代理(CGlib/Jdk)
aop关键词
- 连接点(Joinpoint) 连接点就是加强的实现
- 切点(PointCut)就是那些须要利用切面的办法
加强(Advice)
- 前置告诉(before)
- 后置告诉(after)
- 异样告诉(afterThrowing)
- 返回告诉(afterReturning)
- 盘绕告诉(around)
- 指标对象(Target)
- 织入(Weaving)增加到对指标类具体连接点上的过程。
- 代理类(Proxy) 一个类被AOP织入加强后,就产生了一个代理类。
- 切面(Aspect) 切面由切点和加强组成,它既包含了横切逻辑的定义,也包含了连接点的定义
Spring aop测试
pom
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.5.RELEASE</version> <relativePath/></parent><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency></dependencies>
aspect
@Component@Aspect public class DemoAspect { //切入点1:匹配xxx类下的办法名以demo结尾、参数类型为int的public办法 @Pointcut("execution(public * com.bothsavage.service.DemoService.demo*(int))") public void matchCondition() {} //切入点2:匹配xxx类下的办法名以demo结尾、参数类型为long的public办法 @Pointcut("execution(public * com.bothsavage.service.DemoService.demo1*(long))") public void matchCondition_() {} //前置 @Before("matchCondition()") public void before() { System.out.println("Before"); } //全局后置 @After("matchCondition()") public void after(){ System.out.println("after"); } //返回后置 @AfterReturning("matchCondition()") public void afterReturning(){ System.out.println("afterReturning"); } //抛出后置 @AfterThrowing("matchCondition()") public void afterThrowing(){ System.out.println("afterThrowing"); } @Around("matchCondition_()") public Object around(ProceedingJoinPoint joinPoint) { Object result = null; System.out.println("before"); try{ result = joinPoint.proceed(joinPoint.getArgs());//获取参数 System.out.println("after"); } catch (Throwable e) { System.out.println("after exception"); e.printStackTrace(); } finally { System.out.println("finally"); } return result; }}
service
@Servicepublic class DemoService { public void demo(int arg1){ System.out.println(arg1); } public void demo1(long arg1){ System.out.println(arg1); } }
test
@SpringBootTestpublic class DemoServiceTest { @Autowired DemoService demoService; //测试独自四个 @Test public void testDemo1(){ demoService.demo(1); } //测试around @Test public void testDemo2(){ demoService.demo1(1L); }}
参考
[1].Spring AOP——简略粗犷,小白教学
[2].CGLib动静代理
[3].对于 Spring AOP (AspectJ) 你该通晓的所有
[4].Spring AOP用法详解
本文作者: Both Savage
本文链接: https://bothsavage.github.io/...
版权申明: 本博客所有文章除特地申明外,均采纳 BY-NC-SA 许可协定。转载请注明出处!