MENU

Spring Controller使用AOP无法拦截

May 15, 2022 • 学习笔记

关于使用SpringAOP在Controller里调用内部方法无法拦截的问题

自定义注解如下:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE,ElementType.FIELD})
public @interface Time {
}

Aspect拦截类如下:

@Aspect
@Component
public class TimeAspect {

//    @Around("@annotation(time)")
//    public Object doAround(ProceedingJoinPoint proceedingJoinPoint, Time time) throws Throwable {
//        System.out.println("doAround");
//        return proceedingJoinPoint.proceed();
//    }

    @Around("@annotation(com.example.demo.annotations.Time)")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("doAround");
        return proceedingJoinPoint.proceed();
    }

}

Controller类如下:

@Controller
public class TestController {
    @Time        //注解在这里正常运作
    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String loginPage(){
        testController.test();
        return "login";
    }

    @Time        //注解在这里无法拦截
    public void test(){
        System.out.println("test");
    }
}

在这里如果需要拦截test()方法可以用如下操作:

@Controller
public class TestController {

    @Autowired
    private TestController testController;

    @RequestMapping(path = "/login", method = RequestMethod.GET)
    public String loginPage(){
        testController.test();    //这样调用
        return "login";
    }

    @Time        //这样就可以拦截到
    public void test(){
        System.out.println("test");
    }

}

原因:

。。。