2011-04-05 204 views
3

我已經定義了以下攔截器:彈簧AOP - 切入點/攔截不叫

@Aspect 
public class OpenSessionInRequestInterceptor { 

    private Log log = LogFactory.getLog(getClass()); 

    @Autowired 
    private SessionFactory sessionFactory; 

    public OpenSessionInRequestInterceptor() { 

    } 

    @Around("@annotation(com.sc2.master.aop.hibernate.OpenSession)") 
    public Object processAround(ProceedingJoinPoint pjp) throws Throwable { 
     log.info("Opening Hibernate Session in method "+pjp.getSignature()); 
     Session session = SessionFactoryUtils.getSession(sessionFactory, true); 
     TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); 

     Object ret = pjp.proceed(); 

     session.close(); 
     TransactionSynchronizationManager.unbindResource(sessionFactory); 

     log.info("Closing Hibernate Session in method "+pjp.getSignature()); 

     return ret; 
    } 

} 

當我在一個彈簧測試

@OpenSession 
    public void call() { 
     BusinessCustomer customer = (BusinessCustomer) this.customerDao.loadAll().get(0); 
     System.out.println(customer.getContacts().size()); 
    } 

執行下面的代碼段的方面方法被調用。要開始測試我的測試用例類看起來如下:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations={"file:WebContent/WEB-INF/applicationContext.xml"}) 
@Transactional 

然而,當我有@OpenSession註釋的方法和部署我的Tomcat服務器上的應用程序,攔截方法不叫。

應用程序上下文定義如下所示:

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

<bean id="openSessionInRequestInterceptor" class="OpenSessionInRequestInterceptor"></bean> 

我絕對想不通,爲什麼在tomcat的部署時,AOP不起作用。我希望你有一些想法。

解決方案我找到了解決方案。我將我的aop配置放在applicationContext.xml中,但這不起作用。我將配置放在application-servlet.xml中,現在一切正常。有人知道爲什麼嗎?

回答

2

我承認我沒有使其工作使用的標記註釋,但我需要註釋作爲參數,所以這個工作:

@Around("@annotation(foo)") 
public Object invoke(ProceedingJoinPoint invocation, Foo foo) throws Throwable 

但是...注意@Transactional也開始發生了會話一個沒有開始,所以也許你不需要那個。

更新:如果您的bean是在子上下文中定義的,那麼父上下文的aop配置不會影響它們。父上下文不會看到子上下文,而您的x-servlet.xml是子上下文。

+0

如果我改變我的方法簽名到'public Object processAround(ProceedingJoinPoint pjp,OpenSession openSession)throws Throwable',我得到異常:「引發:java.lang.IllegalArgumentException:錯誤:: 0正式未綁定的切入點」 。 – Erik 2011-04-05 11:47:19

+0

@Erik - 但也改變'@annotation(foo)' - 所以沒有FQN那裏,只是參數名稱。 – Bozho 2011-04-05 11:49:49

+0

好的,現在程序編譯,但仍然沒有調用該方面。是否有某種記錄/調試可以用來查看發生了什麼? – Erik 2011-04-05 12:05:22

1

要回答爲什麼你必須把配置在servlet XML去工作:

我假設你正在使用<context:component-scan ...>標籤,這是擺在servlet的XML。這就是爲什麼你需要將它們都放在servlet XML中,否則它們不會「彼此看」。結果,連接沒有正確建立。