Java CDI@Inject-won';不工作,对象保持为空
我正在尝试使用CDI,使用Java CDI@Inject-won';不工作,对象保持为空,java,netbeans,cdi,Java,Netbeans,Cdi,我正在尝试使用CDI,使用@Inject进行依赖项注入,但我的对象保持为null并且不会初始化。。。更准确地说: 我有一个带有WeatherController的web应用程序,它在我的所有模块中使用java应用程序。在Java应用程序中,我有一个ForecastService,我尝试用CDI初始化存储库,但没有成功。 我试了很多次。希望有人能帮我 我有一个使用此控制器的web应用程序: @Path("/weather") public class WeatherContro
@Inject
进行依赖项注入,但我的对象保持为null
并且不会初始化。。。更准确地说:
我有一个带有WeatherController
的web应用程序,它在我的所有模块中使用java应用程序。在Java应用程序中,我有一个ForecastService
,我尝试用CDI初始化存储库,但没有成功。
我试了很多次。希望有人能帮我
我有一个使用此控制器的web应用程序:
@Path("/weather")
public class WeatherController {
private ForecastService forecastService;
//private ForecastRepository forecastRepository = new ForecastFakeDB();
//private ObservationRepository observationRepository = new ObservationFakeDB();
public WeatherController() {
//this.forecastService.setForecastRepository(forecastRepository);
//forecastService.setObservationRepository(observationRepository);
forecastService = new ForecastService();
}
//localhost:8080/DA_project_weatherPredictions/api/weather/observation/Leuven
@GET
@Produces({"application/json"})
@Path("/observation/{location}")
public Response getObservation(@PathParam("location") String location) {
try {
ObjectMapper mapper = new ObjectMapper();
Observation observation = forecastService.getCurrentObservation(location);
//Object to JSON in String
String jsonInString = mapper.writeValueAsString(observation);
return Response.status(200).entity(jsonInString).build();
} catch (Exception ex) {
System.out.println("error");
System.out.println(ex.getMessage());
ex.printStackTrace();
return null;
}
}
这很好用。这是我的预报服务:
public class ForecastService implements Service {
@Inject
ForecastRepository forecastRepository;
@Inject
ObservationRepository observationRepository;
private Client client;
private WebTarget webTargetObservation, webTargetForecast;
public ForecastService() {
// WeatherRepositoryFactory weatherRepositoryFactory = new WeatherRepositoryFactory();
// forecastRepository = weatherRepositoryFactory.getForecastRepository(repository);
// observationRepository = weatherRepositoryFactory.getObservationRepository(repository);
loadWeather();
}
public void setForecastRepository(ForecastRepository forecastRepository) {
this.forecastRepository = forecastRepository;
}
public void setObservationRepository(ObservationRepository observationRepository) {
this.observationRepository = observationRepository;
}
public void loadWeather() {
//http://api.openweathermap.org/data/2.5/weather?units=metric&appid=12fa8f41738b72d954b6758d48e129aa&q=BE,Leuven
//http://api.openweathermap.org/data/2.5/forecast?units=metric&appid=12fa8f41738b72d954b6758d48e129aa&q=BE,Leuven
client = ClientBuilder.newClient();
webTargetObservation = client.target("http://api.openweathermap.org/data/2.5/weather")
.queryParam("mode", "json")
.queryParam("units", "metric")
.queryParam("appid", "12fa8f41738b72d954b6758d48e129aa");
webTargetForecast = client.target("http://api.openweathermap.org/data/2.5/forecast")
.queryParam("mode", "json")
.queryParam("units", "metric")
.queryParam("appid", "12fa8f41738b72d954b6758d48e129aa");
}
public Observation getCurrentObservation(String location) throws Exception {
Observation observation;
observation = observationRepository.getObservation(location);
if (observation == null) {
try {
//observation = webTargetObservation.queryParam("q", location).request(MediaType.APPLICATION_JSON).get(Observation.class);
Response response = webTargetObservation.queryParam("q", location).request(MediaType.APPLICATION_JSON).get();
String json = response.readEntity(String.class);
//System.out.println(json);
response.close();
observation = new ObjectMapper().readValue(json, Observation.class);
//System.out.println(observation.getWeather().getDescription());
}
catch (Exception e){
StringBuilder sb = new StringBuilder(e.toString());
for (StackTraceElement ste : e.getStackTrace()) {
sb.append("\n\tat ");
sb.append(ste);
}
String trace = sb.toString();
throw new Exception (trace);
//throw new Exception("Location not found");
}
this.observationRepository.addObservation(observation, location);
}
return observation;
}
所以问题是我的存储库保持null
@Alternative
public class ObservationDB implements ObservationRepository{
//as ID we can use the ASCI value of the String key .. example uklondon to ASCII
public ObservationDB(String name) {
}
@Override
public Observation getObservation(String location) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void addObservation(Observation observation, String location) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Mermory DB:
@Default
public class ObservationFakeDB implements ObservationRepository {
//example String key : beleuven, uklondon
private static Map<String, Observation> observations;
public ObservationFakeDB() {
observations = new HashMap<>();
}
@Override
public Observation getObservation(String location) {
return observations.get(location);
}
@Override
public void addObservation(Observation observation, String location) {
observations.put(location, observation);
}
}
您需要让您的CDI容器管理所有bean的生命周期,以允许它正确地解析和注入它们的依赖关系 因此,在您的情况下,您不应该自己创建
ForecastService
的实例,而应该通过简单地用@Inject
注释字段ForecastService
将其委托给CDI容器,这样它的依赖关系将由容器自动解析和设置
public class WeatherController {
@Inject
private ForecastService forecastService;
...
您是否尝试过使用
@Inject
对字段forecastService
进行注释,而不是自己创建它?同时从forecastService
的默认构造函数中删除loadWeather()
,并简单地使用@Inject
对其进行注释,以指示要在init上调用它的CDI容器。您如何调用“我的存储库”?如果我在forecastService上尝试@Inject,我会得到这样的结果:“使用限定符@Default的类型服务的未满足依赖项”我会首先尝试让其他东西工作,然后需要将其注入。我的存储库是我的数据库类,真实数据库或假(内存)数据库
public class WeatherController {
@Inject
private ForecastService forecastService;
...