你要成为想象中的样子,这件事,一步也不能退。
概述
AOP是动态代理思想实现的典型例子,一般在项目中主要是做一些统一性的日志或者错误的处理。
实现
依赖
1 2 3 4 5
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> <version>1.5.4.RELEASE</version> </dependency>
|
代码
1 2 3 4 5
| @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface Action { String value() default "" ; }
|
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
| @Component @Aspect public class LogAspect {
@Pointcut("@annotation(com.stack.config.annotation.Action)") public void logPointCut (){ }
@Pointcut("execution(* com.stack.config.controller.TaskController.*(..))") public void controllerPointCut() { } @Around("logPointCut()") public Object around (ProceedingJoinPoint point) throws Throwable { Object result = null ; try{ System.out.println("方法执行开始。。。"); Signature signature = point.getSignature(); System.out.println("方法名:"+signature.getName()); Object[] args = point.getArgs(); System.out.println("请求参数:"+ JSON.toJSONString(args)); result = point.proceed(); } catch (Exception e){ } return result; }
@Around("controllerPoint()&& args(arg)") public Object controllerMethodAround(ProceedingJoinPoint point,String arg) throws Throwable { System.out.println(arg); Signature signature = point.getSignature(); System.out.println(signature.getName()); Object result = point.proceed();
System.out.println(result); return result; } }
|
1 2 3 4 5 6 7 8 9
| @Service public class CountImpl implements ICount { @Override @Action public int add(int a,int b) { return a+b; } }
|
切点表达式
1
| execution (* com.sample.service.impl..*.*(..))
|
整个表达式可以分为五个部分:
https://blog.csdn.net/lang_niu/article/details/51559994