Intercepting method with Spring AOP using only annotations

帅比萌擦擦* 提交于 2019-12-01 10:39:24

Have you enabled annotation-based AOP? The documentation says you have to add

<aop:aspectj-autoproxy/>

to your spring configuration. Then you need to add an annotation in front of your checkUser method. It looks like you want @Around advice, as described here.

@Aspect
public class UserExistsCheck {

  @Around("execution(* a.b.c.d.*.*(..)) && args(a.b.c.d.RequestObject)")
  public Object checkUser(ProceedingJoinPoint pjp) throws Throwable {
RTBarnard

From the example code you've provided, it appears that you're trying to create advice for a class that doesn't implement any interfaces. As described in the Proxying Mechanisms section of the Spring docs, if you're going to do this, you'll need to enable CGLIB:

<aop:aspectj-autoproxy proxy-target-class="true" />

I've personally found this to be a bit more finicky than the documentation indicates it should be, and though it does work if all of the stars are aligned just right, it's often easier--and preferable from a design standpoint--to declare your AOP advice on an interface, as follows. (Note that you'll need to obtain your instance of KlazzImpl from your BeanFactory/ApplicationContext.)

public interface Klazz {
  ResponseObject doSomething(RequestObject request);
}

public class KlazzImpl implements Klazz {
  public ResponseObject doSomething(RequestObject request) {...}
}

Additionally, your use of the args expression is a little bit off. See the following:

@Aspect
public class UserExistsCheck {
  @Autowired
  private UserInformation userInformation;

  @Around("execution(* a.b.c.d.*.*(..)) && args(reqObj)")
  public Object checkUser(ProceedingJoinPoint pjp, a.b.c.d.RequestObject reqObj) throws Throwable {
      // ...
  }
}

These changes should do the job.

since spring 3.1 add @EnableAspectJAutoProxy(proxyTargetClass=true) to your @Configuraiton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!