2013-10-28 51 views
0

我正在使用Apache-CXF開發的REST服務。我使用Spring 3.1註解來連接bean。我編寫了一個截取我的REST方法用於監視目的的攔截器。要做到這一點,我必須autowire我的監控類,這是在我的項目中添加爲圖書館。 @Autowired似乎沒有在這種情況下工作,並導致NPE。我在這裏做錯了什麼?@Autowired無法使用攔截器

@Aspect 
@Component 
public class ApplicationMonitoring { 

Logger logger = LoggerFactory.getLogger(ApplicationMonitoring.class); 

@Autowired 
private Monitor monitor; 

@Around("execution(* com.abc.xyz.rest.CustomerResource.getCustomerByAccountNumber(..))") 
public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { 
    String methodName = joinPoint.getSignature().getName(); 

    long start = System.currentTimeMillis(); 
    try { 
     // proceed to original method call 
     Object result = joinPoint.proceed(); 
     monitor.elapsedTime(methodName, System.currentTimeMillis() - start); 
      return result; 
    } catch (Exception e) { 
     throw e; 
    } 
} 

的ApplicationContext:

................. 
...... 
<context:spring-configured /> 

<context:component-scan base-package="com.abc"> 
    <context:exclude-filter expression="org.springframework.stereotype.Controller" 
     type="annotation" /> 
</context:component-scan> 

<context:annotation-config/> 

............. 
+0

你可以在這個'@Aspect'上顯示你的組件掃描的上下文嗎? –

+0

@SotiriosDelimanolis我已經用applicationContext更新了原始文章 – Pankaj

+0

當Spring bean有註釋應該最終生成2個代理(例如Transactional和Aspects)時,通常會發生此問題。 Spring能夠生成其中一個代理,但是它會「丟失」元數據來創建第二個代理。避免這種情況的一個方法是使用aspectj編譯時編織器,因爲在編譯時會添加一些方面。 – Augusto

回答

0

發現在this blog

的ASPE溶液ct是一個單例對象,並在Spring容器外創建。具有XML配置的解決方案是使用Spring的工廠方法來檢索方面。

<bean id="monitoringAspect" class="com.myaapp.ApplicationMonitoring" 
    factory-method="aspectOf" /> 

使用此配置時,該方面將被視爲任何其他Spring bean,並且自動裝配將正常工作。

0

我不是春天的高手,但據我所知,有些地方我會盡量投入的話是最好的,我可以。

我想你注意到了,但@Aspect不是基於彈簧的,所以爲了掃描它,你需要添加<aop:aspectj-autoproxy/>,此外我認爲問題是創建了兩個相同類的實例,一個用於每個容器(spring和AspectJ),以避免我使用工廠方法來檢索完全相同的實例到spring容器(如果我正確解釋它,我不能確定它是100%) - 請記住,爲方面創建第一代,以這樣的方式:

<bean id="id_of_your_bean" class="ApplicationMonitoring" factory-method="aspectOf"> 
    //other stuff 
</bean>