Spring_AOP切面

239 阅读1分钟

定义注解

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {   
    String module() default "";  // 模块名
    String description() default ""; // 描述
}

定义切面

@Aspect
@Component
public class LogAspect {
    @Pointcut("@annotation(LogAnnotation)")
    public void apiRequestLogAspect() {
    }

    @Around("apiRequestLogAspect()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        System.out.println("================执行前==================");
        Object proceed = point.proceed();
        System.out.println("================执行后==================");
        return proceed;
    }
}

定义service

@Component
public class UserService{
    @LogAnnotation
    public void sayHello() {
        System.out.println("Hello World");
    }
}

定义controller

@GetMapping("/testAspect")
public void testAspect(HttpServletRequest request) {
    userService.sayHello();
}