问题
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