Injection CDI of Interface Returns NullPointerException

女生的网名这么多〃 提交于 2019-12-25 07:59:26

问题


I have a problem with the injection in Java as I would like to inject an interface called RemoteStatisticService but it keeps returning null in this case thus error NullPointerException. I have tried to follow this with init() method and @PostConstruct but still gives me the same error.

Here is the code for MeasurementAspectService class:

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() {

    }

}

Here is the code for interface class 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);

}

Any help is appreciated. Thanks


回答1:


The problem is that you've defined an aspect using aspectj but are trying to get a reference to a CDI bean. This isn't going to work.

This line here is the culprit:

private final MeasurementAspectService measurementAspectService = new MeasurementAspectService();

You'll need to use CDI to get a reference. If you're using CDI 1.1, you can use this snippet.

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

This is because AspectJ isn't intended for CDI use. Note that you can use interceptors in CDI as well.




回答2:


CDI 1.1+ works with implicit beans by default. You need to add a bean-defining annotation like @Dependent or @ApplicationScoped to any class you want to get picked up by CDI.



来源:https://stackoverflow.com/questions/37343280/injection-cdi-of-interface-returns-nullpointerexception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!