2016-05-20 49 views
0

我有一個Java注入問題,因爲我想注入一個名爲RemoteStatisticService的接口,但它在這種情況下一直返回null,因此錯誤爲NullPointerException。我試圖用init()方法和@PostConstruct來關注this,但仍然給我提供了同樣的錯誤。注入CDI的接口返回空指針異常

下面是MeasurementAspectService類的代碼:

import javax.annotation.PostConstruct; 
import javax.inject.Inject; 

import *.dto.MeasureDownloadDto; 
import *.dto.MeasureUploadDto; 
import *.rs.RemoteStatisticService; 

public class MeasurementAspectService { 

    private @Inject RemoteStatisticService remoteStatisticService; 

    public void storeUploadDto(MeasureUploadDto measureUploadDto) { 

     remoteStatisticService.postUploadStatistic(measureUploadDto); 

    } 

    public void storeDownloadDto(MeasureDownloadDto measureDownloadDto) { 

     remoteStatisticService.postDownloadStatistic(measureDownloadDto); 

    } 

    @PostConstruct 
    public void init() { 

    } 

} 

這是任何幫助表示讚賞接口類RemoteStatisticService

import static *.util.RemoteServiceUtil.PRIV; 

import javax.ws.rs.Consumes; 
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 

import *.dto.MeasureDownloadDto; 
import *.dto.MeasureUploadDto; 

@Path(PRIV + "stats") 
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) 
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) 
public interface RemoteStatisticService { 
    @POST 
    @Path("upload") 
    void postUploadStatistic(MeasureUploadDto mud); 

    @POST 
    @Path("download") 
    void postDownloadStatistic(MeasureDownloadDto mdd); 

} 

的代碼。謝謝

+0

爲了有效注入,他們需要標記爲'@ Named' bean供CDI提供者處理,例如。 'Weld' – PDStat

+0

在這種情況下,我應該在哪裏放置@named bean?我正在使用Maven,並且仍然與CDI一起使用 –

+0

在課程級別,例如。 '@Named public class MeasurementAspectService' – PDStat

回答

0

默認情況下,CDI 1.1+使用隱式bean。你需要添加一個bean定義的註釋,如@Dependent@ApplicationScoped到你想要被CDI拾取的任何類。

1

問題是,您已經使用aspectj定義了一個方面,但正試圖獲得對CDI bean的引用。這是行不通的。

這裏這行是罪魁禍首:

private final MeasurementAspectService measurementAspectService = new MeasurementAspectService();

你需要使用CDI得到一個參考。如果您使用CDI 1.1,則可以使用此片段。

private final MeasurementAspectService measurementAspectService = CDI.current().select(MeasurementAspectService.class).get();

這是因爲AspectJ是不適合使用CDI。請注意,您也可以在CDI中使用interceptors

+0

有一個CDI錯誤,因爲它無法獲取引用它。我是否需要導入另一個包?我正在使用Maven,我相信我使用的是從版本1.1.0的javax.validation組(工件驗證-api)導入的Javax包.Final –

+0

好的我修復了以前的錯誤,現在新的錯誤是「Exception while initializing MeasurementAspect:java.lang.IllegalStateException:無法找到CDIProvider「 –

+0

您確定您正在使用CDI嗎? –