接口的注入 CDI 返回 NullPointerException



我在Java中的注入有问题,因为我想注入一个名为RemoteStatisticService的接口,但在这种情况下它一直返回null,因此错误NullPointerException。我尝试使用 init() 方法和 @PostConstruct 遵循这一点,但仍然给我同样的错误。

以下是 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() {
    }
}

下面是接口类远程统计服务的代码

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

任何帮助,不胜感激。谢谢

问题是你已经使用 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 中使用拦截器。

CDI 1.1+ 默认使用隐式 bean。您需要将 Bean 定义注释(如 @Dependent@ApplicationScoped)添加到您希望由 CDI 拾取的任何类中。

最新更新