天天看點

SpringBoot ~ AOP切面程式設計

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();
        }
    }