【问题标题】:AOP Spring @AfterReturning not calling the aspects method properlyAOP Spring @AfterReturning 没有正确调用切面方法
【发布时间】:2019-04-15 10:19:54
【问题描述】:

我有一个注释。


@Target(value = {ElementType.METHOD, ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyCustomAnnotation{

}

我的 Aspect 类是这样的


@Component
@Aspect
public class MyCustomAsspect{

    @AfterReturning(
            pointcut="@annotation(MyCustomAnnotation)",
            returning="retVal")
    public void publishMessage(JoinPoint jp, Object retVal) throws Throwable {


    }
}

我的服务类是

@Service
public class ServiceClass{

@MyCustomAnnotation
public Object someMethod(){
return new Object();
}

}

上面提到的类我不知道为什么我的方面不起作用。我是 Spring AOP 的新手。请帮助我,将非常感谢。

【问题讨论】:

  • 你的切入点到底是什么?
  • 你缺少切入点或切入点不当
  • @annotation(MyCustomAnnotation) 这是我的切入点
  • 尝试在 MyCustomAsspect 类上方添加 @EnableAspectJAutoProxy
  • @BishalJaiswal 它已经出现在我的 SpringBootApplication 类中

标签: java spring aop spring-aop aspect


【解决方案1】:

问题是由于切入点声明。正如春季文档所说

@annotation - 限制匹配到连接点 连接点(在 Spring AOP 中执行的方法)具有给定的 注释

所以我下令完成这项工作

@Aspect
public class MyCustomAsspect{

    @AfterReturning(
            pointcut="execution(public * *(..)) and @annotation(MyCustomAnnotation)",
            returning="retVal")
    public void publishMessage(JoinPoint jp, Object retVal) throws Throwable {


    }
}

【讨论】:

  • 我不知道为什么 OP 接受了这个答案,因为 IMO 它不能解决问题。附加的execution(public * *(..)) and 不会以任何方式改变方面的行为。因此,无论解决了 OP 的问题,它一定是别的东西。我只是对此发表评论,以便没有人相信这是一个真正的解决方案。例如,像@annotation(my.package.MyCustomAnnotation) 这样的完全限定类名之类的东西更有可能实际解决了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-26
  • 1970-01-01
相关资源
最近更新 更多