springboot(5)AOP代理
祈雨的笔记
·
2018-01-22
·
via 祈雨的笔记
1、启动aop代理
添加maven依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
|
向springboot的入口类添加注解@EnableAspectJAutoProxy,使注解@Aspect生效。
2、aspect代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| @Aspect @Component public class TestAspect {
@Before("execution(* com.example.demo.action.*.* (..))") public void testBefore() { System.out.println("before"); }
@After("execution(* com.example.demo.action.*.* (..))") public void testAfter() { System.out.println("after"); }
@Around("execution(* com.example.demo.action.*.* (..))") public Object testAround(ProceedingJoinPoint pjp) throws Throwable { System.out.println("before"); Object result = pjp.proceed(); System.out.println("==========="+result); System.out.println("after"); return result; }
@AfterThrowing(pointcut="execution(* com.example.demo.action.*.* (..))",throwing="e") public void testThrowing(Exception e) { System.out.println(e.getMessage()); } }
|
3、pointcut表达式
常用的pointcut表达式为execution,格式如下:
execution([访问修饰符] 返回类型 [申明类型] 方法名(参数名) [异常名])
|表达式|效果|
|—–|—–|—–|
|execution(public * * (..))|任意公共方法|
|execution(* set* (..))|任意方法名以”set”开头的方法|
|execution(* com.wxtx.TestDao.* (..))|com.wxtx.TestDao类下的任意方法|
|execution(* com.wxtx.. (..))|com.wxtx包(不包括子包)下的任意方法|
|execution(* com.wxtx... (..))|com.wxtx包及其子包下的任意方法|
|within(com.wxtx.service.)|com.wxtx.service包(不包括子包)下的任意方法|
|within(com.wxtx.service..)|com.wxtx.service包(不包括子包)下的任意方法|
|this(com.wxtx.service.TestService)|实现了com.wxtx.service.TestService接口的代理对象的任意方法|
|target(com.wxtx.service.TestService)|实现了com.wxtx.service.TestService接口的目标对象的任意方法|
|args(java.io.Serializable)|任意只接受一个参数,且该参数类型是java.io.Serializable的方法|
|bean(testService)|spring容器中bean名为testSerivce的bean的任意方法|
|bean(Service)|spring容器中bean名匹配Serivce的bean的任意方法|
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。