2013-05-13 102 views
2

我只在具有CDI(焊接)和JPA(休眠)的Servlet容器(Tomcat)中工作。我發現在網上建立一個「事務性」攔截器的例子很多:CDI:如何將攔截器應用於庫(第三方)代碼?


import java.lang.annotation.Documented; 
import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 
import javax.interceptor.InterceptorBinding; 

@Target({ ElementType.METHOD, ElementType.TYPE }) 
@Retention(RetentionPolicy.RUNTIME) 
@Documented 
@InterceptorBinding 
public @interface Transactional {} 

@Transactional 
@Interceptor 
public class TransactionalInterceptor { 
    @Inject EntityManager em; 

    @AroundInvoke 
    public Object wrapInTransaction(InvocationContext invocation) throws Exception { 
    boolean transactionOwner = !isTransactionInProgress(); 

    if (transactionOwner) { 
     em.getTransaction().begin(); 
    } 

    try { 
     return invocation.proceed(); 
    } 
    catch (RuntimeException ex) { 
     em.getTransaction().setRollbackOnly(); 
     throw ex; 
    } 
    finally { 
     if (transactionOwner) { 
     if (em.getTransaction().getRollbackOnly()) { 
      em.getTransaction().rollback(); 
     } 
     else { 
      em.getTransaction().commit(); 
     } 
     } 
    } 
    } 

    private boolean isTransactionInProgress() { 
    return em.getTransaction().isActive(); 
    } 
} 

而且在我的本地代碼這個偉大工程。但是,我希望能夠應用這個Transactional註解(攔截器)來編寫我沒有寫的代碼(即我使用的庫代碼)。就我而言,我希望將CDI攔截器應用於Struts2攔截器,以確保在整個處理請求期間,我將打開一個事務。

如何以這種方式將此Transactional攔截器應用於庫代碼?

編輯這事,我已經通過Spring XML以前做的:

<!-- TRANSACTIONAL DEMARCATION --> 
<aop:config> 
    <aop:pointcut id="transactionalPointCut" expression="execution(* utils.struts2.interceptor.TransactionInterceptor.intercept(..))"/> 
    <aop:advisor pointcut-ref="transactionalPointCut" advice-ref="transactionalAdvice"/> 
</aop:config> 
... 

但是我正在尋找的CDI替代。

回答

2

這對於CDI 1.0來說變得困難。你必須打開jar並在META-INF中添加一個beans.xml文件,重新打包這個jar文件並在你的戰爭中(我認爲這是一場戰爭)創建一個可移植的擴展,將元數據攔截器註釋添加到類中。您需要注意BeforeBeanDiscovery並添加新的AnnotatedType。 DeltaSpike可以幫助那部分。

+0

如果它有所作爲,我正在使用CDI 1.1(焊接2.0.0)。我會看看DeltaSpike來幫助我在'BeforeBeanDiscovery'觀察事件中創建一個新的'AnnotatedType'。感謝您指點我正確的方向。 – 2013-05-14 15:04:24

+0

沒問題,希望對你有用。 – LightGuard 2013-05-14 18:32:11

相關問題