使用Spring AOP仅使用注释的拦截方法

fis*_*ish 3 java spring annotations spring-aop

在我的Spring上下文文件中,我有这样的东西:

<bean id="userCheck" class="a.b.c.UserExistsCheck"/>
<aop:config>
      <aop:aspect ref="userCheck">
         <aop:pointcut id="checkUser"
                expression="execution(* a.b.c.d.*.*(..)) &amp;&amp; args(a.b.c.d.RequestObject)"/>
         <aop:around pointcut-ref="checkUser" method="checkUser"/>
      </aop:aspect>
</aop:config>    
Run Code Online (Sandbox Code Playgroud)

abcUserExistsCheck看起来像这样:

@Aspect
public class UserExistsCheck {

@Autowired
private UserInformation userInformation;

public Object checkUser(ProceedingJoinPoint pjp) throws Throwable {
    int userId = ... //get it from the RequestObject passed as a parameter
    if (userExists(userId)) {
        return pjp.proceed();
    } else {
        return new ResponseObject("Invalid user);
    }
}
Run Code Online (Sandbox Code Playgroud)

被这些东西拦截的类看起来像这样:

public class Klazz {
    public ResponseObject doSomething(RequestObject request) {...}
}
Run Code Online (Sandbox Code Playgroud)

这有效.在将呼叫传递给Klazz之前,会根据需要执行UserExistCheck.问题是,这是我让它运作的唯一方法.通过使用注释而不是上下文文件来实现这一点似乎对我的小脑子来说太过分了.那么......我究竟应该如何在UserExistsCheck和Klazz中注释方法?我还需要其他东西吗?另一堂课?上下文文件中还有什么内容?

Joh*_*ohn 5

您是否启用了基于注释的AOP?该文件说,你必须添加

<aop:aspectj-autoproxy/>
Run Code Online (Sandbox Code Playgroud)

你的弹簧配置.然后,您需要在checkUser方法前添加注释.看起来你想要@Around建议,如这里所述.

@Aspect
public class UserExistsCheck {

  @Around("execution(* a.b.c.d.*.*(..)) && args(a.b.c.d.RequestObject)")
  public Object checkUser(ProceedingJoinPoint pjp) throws Throwable {
Run Code Online (Sandbox Code Playgroud)