Intercepting method with Spring AOP using only annotations

前端 未结 3 1789
清酒与你
清酒与你 2021-01-14 10:47

In my Spring context file I have something like this:



      

        
3条回答
  •  北海茫月
    2021-01-14 11:23

    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:

    
    

    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.

提交回复
热议问题