簡體   English   中英

使用Spring AOP僅使用注釋的攔截方法

[英]Intercepting method with Spring AOP using only annotations

在我的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>    

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);
    }
}

被這些東西攔截的類看起來像這樣:

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

這有效。 在將呼叫傳遞給Klazz之前,會根據需要執行UserExistCheck。 問題是,這是我讓它運作的唯一方法。 通過使用注釋而不是上下文文件來實現這一點似乎對我的小腦子來說太過分了。 那么......我究竟應該如何在UserExistsCheck和Klazz中注釋方法? 我還需要其他東西嗎? 另一堂課? 上下文文件中還有什么內容?

您是否啟用了基於注釋的AOP? 文檔說你必須添加

<aop:aspectj-autoproxy/>

你的彈簧配置。 然后,您需要在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 {

從您提供的示例代碼中,您似乎正在嘗試為未實現任何接口的類創建建議。 如Spring文檔的Proxying Mechanisms部分所述,如果您要執行此操作,則需要啟用CGLIB:

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

我個人認為這比文檔指出的要復雜得多,雖然如果所有的星星都正確對齊,它確實有效,但從設計的角度來看,通常更容易宣布您對接口的AOP建議如下。 (請注意,您需要從BeanFactory / ApplicationContext獲取KlazzImpl實例。)

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

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

另外,你對args表達式的使用有點偏。 請參閱以下內容:

@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 {
      // ...
  }
}

這些變化應該起到作用。

從3.1開始,將@EnableAspectJAutoProxy(proxyTargetClass=true)@Configuraiton

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM