Spring AOP

1. pom依赖

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2. 自定义注解

/**
 * MyLog
 *
 * @Author zpf
 * @Date 2020-06-16 22:52:49
 */
@Documented
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Clc {
    String value();
    String name() default "";
}

3. 切面

/**
 * MyAspectJ
 *
 * @Author zpf
 * @Date 2020-06-16 22:54:25
 */
@Component
@Aspect
public class MyAspectJ {

    /**
     *  方法一: 通过自定义注解 好处: 注解自定义,想放哪放哪,比较灵活,但是对于批量切入某些类不适用
     */
    @Pointcut("@annotation(com.royal.framework.annotations.Clc)")
    public void pointCut() {}

    /**
     *  方法二: 通过切入某些类 好处:对于某些类,可以进行统一管理
     *
     */
//    @Pointcut("execution(* com.royal.framework.controller.*.*(..))")
//    public void pointCut() {}

    @Around("pointCut()")
    public Object deBefore(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("---------方法执行之前-------------");
        // 执行原方法,并记录返回值。
        Object proceed = pjp.proceed();
        System.out.println("---------方法执行之后-------------");
        return proceed;
    }
}

4. 控制器层测试

/**
 * TestController
 *
 * @Author zpf
 * @Date 2020-06-16 22:52:03
 */
@RestController
public class TestController {

    @GetMapping("/index")
    @Clc(value = "测试",name = "test")
    public String getIndex(String username){
        System.out.println("userName=" + username);
        return "This is index";
    }
}

相关推荐