1.项目描述
写一个批量导入功能,这里我用的是ExcelKit。
2.整合
这里不做多介绍,直接去作者文档看Git地址
3.主要问题
ExcelKit有一个校验功能,需要实现它的Validator接口,重写valid方法即可。这里贴一段代码
@Component
public class StudentDeptValidator implements Validator {
@Resource
private IDeptService deptService;
@Override
public String valid(Object value) {
String course = (String) value;
if(course == null){
return "班级不能为空";
}
Dept dept = deptService.getOne(new QueryWrapper<Dept>().lambda().eq(Dept::getDeptName, course));
if(dept==null){
return "暂无该班级,请核实班级名称";
}
return null;
}
}
验证方法少不了会有一些逻辑代码,这里我就注入了一个service,想着也没啥问题,但是一测试,发现Bug了,如下图
deptService直接空指针了。对此我很纳闷,检查了一下代码,该有的注解,一个也没少。怎么会空指针呢,想了一会,想到了生命周期。在上面的代码中,我们又调用了另一个bean进行操作,而此时,另一个bean还未被注入,从而会引起空指针问题。
4.解决方法
@Component
public class StudentDeptValidator implements Validator {
private static StudentDeptValidator studentDeptValidator;
@Resource
private IDeptService deptService;
@PostConstruct
public void init(){
studentDeptValidator = this;
studentDeptValidator.deptService = this.deptService;
}
@Override
public String valid(Object value) {
String course = (String) value;
if(course == null){
return "班级不能为空";
}
Dept dept = studentDeptValidator.deptService.getOne(new QueryWrapper<Dept>().lambda().eq(Dept::getDeptName, course));
if(dept==null){
return "暂无该班级,请核实班级名称";
}
return null;
}
}
@PostContruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。