【问题标题】:When to use @Pointcut & @Before, @After AOP Annotations何时使用@Pointcut & @Before、@After AOP 注解
【发布时间】:2017-05-08 09:25:41
【问题描述】:

我正在学习 Spring 中的 AOP 概念。我现在非常了解 @Before@After 注释的用法,并开始将其用于时间捕获目的。

这几乎满足了我所有与 AOP 相关的需求。想知道每个春季指南都谈到的@pointcut 注释是什么吗?那是多余的功能吗?还是有单独的需求?

【问题讨论】:

    标签: spring spring-mvc spring-aop


    【解决方案1】:

    简单来说,你在@Before 或@After 中指定的任何内容都是一个切入点表达式。可以使用 @Pointcut 注释将其提取到单独的方法中,以便更好地理解、模块化和更好地控制。例如

        @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
        public void requestMapping() {}
    
        @Pointcut("within(blah.blah.controller.*) || within(blah.blah.aspect.*)")
        public void myController() {}
    
        @Around("requestMapping() && myController()")
        public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
          ...............
       }  
    

    如您所见,您可以使用@Pointcut 将其分成两个方法,而不是在@Around 中指定切入点表达式。

    【讨论】:

    • 谢谢。所以这意味着我可以将Pointcut 表达式用于方法,并且我需要在BeforeAfter&Around 等任何注释中使用这些方法。我说的对吗?
    • 是的。将其视为函数声明。您获取一些代码并将其放入函数中。这使您的业务逻辑代码更加简洁,还可以帮助您在其他地方重用这段代码而不是重复
    • 嗨,您能告诉我ProceedingJoinPoint joinPoint 的用途吗?如何通过?
    • 假设你有一个接受参数的函数,你想给它一个方面。然后可以使用 ProceedingJointPoint 在您的方面获得传递给该函数的参数。在方面结束时,您必须说 joinPoint.proceed() 才能将调用转发给该函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2011-10-23
    相关资源
    最近更新 更多