0

我在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) {}
    }
}

IntegrateMongo在 Github 上查看我的分支可能更容易查看更多详细信息。https://github.com/georgeotoole/T2ClaimsPortal/tree/IntegrateMongo

我不明白我的代码是否有问题,或者我的机器上的 mongo 是否有问题..?

谢谢

4

1 回答 1

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);
}
于 2013-10-15T10:40:18.297 回答