我在AlertService#findAll()
方法上得到NullPointerException:
java.lang.NullPointerException
com.t2.claims.services.AlertService.findAll(AlertService.java:24)
com.t2.claims.controllers.AlertIndexController.doAfterCompose(AlertIndexController.java:28)
这是findAll()方法:
public List<Alert> findAll() {
Query query = new Query(where("id").exists(true));
return mongoTemplate.find(query, Alert.class);
}
整个AlertService就是这样:
package com.t2.claims.services;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.t2.claims.models.Alert;
import static org.springframework.data.mongodb.core.query.Criteria.where;
@Service("alertService")
@Transactional
public class AlertService {
@Resource(name="mongoTemplate")
private MongoTemplate mongoTemplate;
public List<Alert> findAll() {
Query query = new Query(where("id").exists(true));
return mongoTemplate.find(query, Alert.class);
}
public void add(Alert alert) {
try {
mongoTemplate.insert(alert);
} catch(Exception e) {}
}
public void update(Alert alert) {
Query query = new Query(where("id").is(alert.getId()));
try {
Update update = new Update();
update.set("assignedUser", alert.getAssignedUser());
update.set("status", alert.getStatus());
update.set("category", alert.getCategory());
update.set("vehicleStatus", alert.getVehicleStatus());
update.set("brand", alert.getBrand());
mongoTemplate.updateMulti(query, update, Alert.class);
} catch(Exception e) {}
}
public void delete(Alert alert) {
try {
Query query = new Query(where("id").is(alert.getId()));
// Run the query and delete the entry
mongoTemplate.remove(query, Alert.class);
} catch(Exception e) {}
}
}
在Github上查看我的IntegrateMongo
分支可能更容易查看更多细节。 https://github.com/georgeotoole/T2ClaimsPortal/tree/IntegrateMongo
我无法理解我的代码或我的机器上是否存在mongo问题。?
由于
答案 0 :(得分:1)
我很确定这是......的案例:
@Resource(name="mongoTemplate")
private MongoTemplate mongoTemplate;
......没有被注射。
如何在使用mongoTemplate
的方法中添加空检查以确保它已被注入?
public List<Alert> findAll() {
Query query = new Query(where("id").exists(true));
if (mongoTemplate == null) {
throw new IllegalStateException("mongoTemplate is null");
}
return mongoTemplate.find(query, Alert.class);
}