今天写SpringBoot程序,使用MongoTemplate对数据进行处理。出现了NullPointerException,经过Debug发现是在某个类里mongoTemplate为null,但是在别的类中mongoTemplate是没问题的。百度不到解决方案,最后还是用谷歌搜到了适合我的解决方案(人生苦短,我用谷歌)。
可以在该类里不绑定MongoTemplate,在构造方法里初始化MongoTemplate:
@Component
public class AuthorPaper2json {
@Autowired
public AuthorPaper2json(MongoTemplate mongoTemplate){
this.mongoTemplate = mongoTemplate;
}
private final MongoTemplate mongoTemplate;
public void saveAsJson(String name) throws IOException {
List<Paper_info> paperInfoList;
Query query = new Query();
query.addCriteria(Criteria.where("index").is(name));
paperInfoList = mongoTemplate.find(query, Paper_info.class);
List<JSONObject> jsonObjectList = new ArrayList<>();
for(Paper_info item:paperInfoList){
try{
String jsonStr = JSON.toJSONString(item);
JSONObject jsonObject = (JSONObject)JSON.parse(jsonStr);
jsonObjectList.add(jsonObject);
} catch (Exception e){
e.printStackTrace();
}
JSONObject jsonContainer = new JSONObject();
jsonContainer.put("msg","");
jsonContainer.put("count",paperInfoList.size());
jsonContainer.put("code",0);
jsonContainer.put("data",jsonObjectList);
File file = new File("src/main/resources/static/"+name+".json");
FileWriter fileWriter = new FileWriter(file,false);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(jsonContainer.toJSONString());
bufferedWriter.close();
}
}
在调用该类的时候,再给该类初始化MongoTemplate。