SpringBoot ~ AOP切面编程

  1. 云栖社区>
  2. 博客>
  3. 正文

SpringBoot ~ AOP切面编程

wsyjlly 2019-08-12 13:37:03 浏览94
展开阅读全文

AOP切面编程

  1. 添加pom依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
  2. 编写切面类

    /**
     * @author wsyjlly
     * @create 2019.06.14 - 17:23
     **/
    @Aspect
    public class LogAspect {
        @Pointcut("execution(* cn.wsyjlly.controller.*.*(..))")
        public void pc(){}
    
        @Before(value="pc()")
        public void before(JoinPoint jp){
            String name = jp.getSignature().getName();
            System.out.println(name+"方法开始执行...");
            System.out.println(name+"——————————————————————————————");
        }
    
        @After(value = "pc()")
        public void after(JoinPoint jp){
            String name = jp.getSignature().getName();
            System.out.println(name+"——————————————————————————————");
            System.out.println(name+"方法执行结束...");
        }
    
        @AfterReturning(value = "pc()" , returning = "result")
        public void afterReturning(JoinPoint jp,Object result){
            String name = jp.getSignature().getName();
            System.out.println(name+"方法返回值为:"+result);
        }
    
        @AfterThrowing(value = "pc()" , throwing = "e")
        public void afterThrowing(JoinPoint jp,Exception e){
            String name = jp.getSignature().getName();
            System.out.println(name+"方法抛出异常:"+e.getClass().getName());
        }
    
        @Around("pc()")
        public Object around(ProceedingJoinPoint pjp) throws Throwable{
            return pjp.proceed();
        }
    }

网友评论

登录后评论
0/500
评论
wsyjlly
+ 关注