【问题标题】:Spring and AOP : @After works but not @AfterReturningSpring 和 AOP:@After 有效,但 @AfterReturning 无效
【发布时间】:2015-09-17 23:49:44
【问题描述】:

在 web 应用程序中,我使用 Spring AOP 来检查我的服务在传入呼叫时的授权,并在返回结果时管理消息(信息、警告、错误)。使用切面来节省我的代码行并概括我的服务的行为(看起来很性感^^)。

所以我的应用上下文中有这种类型的 conf

    <aop:aspectj-autoproxy />
    <bean id="authenticationCheckAspect" class="fr.test.server.business.aspect.AuthenticationCheckAspect" />

我的方面看起来像这样:

package fr.test.server.business.aspect;

@Aspect
public class AuthenticationCheckAspect {

    private static final Logger LOG = LoggerFactory.getLogger(AuthenticationCheckAspect.class);

    @Autowired
    private AuthenticationBiz authBiz;

    /**
     * methodAnnotatedWithMyService Pointcut
     */
    @Pointcut("execution(@fr.test.server.business.aspect.MyService * *(..))")
    public void methodAnnotatedWithMyService() {
        // Méthode vide servant de Pointcut
    }

    @Before("methodAnnotatedWithMyService()")
    public void checkAuthentication(final JoinPoint joinPoint) throws FunctionalException {
        LOG.debug("checkAuthentication {}", joinPoint);

        {process...}
    }

    @AfterReturning(pointcut = "methodAnnotatedWithMyService()", returning = "result")
    public void manageErrors(final JoinPoint joinPoint, final Object result) {
        LOG.debug("Returning {}", joinPoint);
    }
}

在执行任何标记为@MyService 的方法之前,应该触发checkAuthentication() 方法,它是:) 那是一种解脱。

在执行任何标记为@MyService 的方法后,方法manageErrors 也应该被触发,但它没有:( 请注意,使用@After,它可以工作,但我绝对需要我的@MyService 的返回值带注释的方法,这就是为什么我需要@AfterReturning

由于我的@Before 建议有效(以及@After 在我尝试时也有效),我想我没有代理类或类似的问题,否则什么都不会发生,但我真的不明白为什么我的@AfterReturning 建议未被调用。

注意:执行呼叫时我没有收到任何错误。只是我的@AfterReturning 建议没有做任何事情:(

有什么想法吗?谢谢!

【问题讨论】:

    标签: java spring aspectj aop


    【解决方案1】:

    您的代码看起来不错。 我会建议添加

    @AfterThrowing(pointcut = "methodAnnotatedWithMyService()",  throwing="ex")
      public void doRecoveryActions( Exception e) {
        // Some code may be System.out.println 
        // or e.printStackTrace()
      }
    

    看看这是否正在执行。

    如果在切入点methodAnnotatedWithMyService() 中抛出异常,则不会调用@AfterReturning.. 但会调用@After..

    来自http://static.springsource.org/spring/docs/2.0.x/reference/aop.html

    @AfterReturning 通知在匹配的方法执行正常返回时运行

    【讨论】:

    • 这只是复制错误^^我刚刚编辑了我的问题。正如我之前所说,我的代码使用 @After 建议。
    • @AfterThrowing 建议的使用帮助很大。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多