背景:使用@value注解为类的静态属性赋值的时候,发现一直是空。为什么会这样呢?
Spring 依赖注入 是依赖 set方法,set方法是 是普通的对象方法,也就是类实例化的时候才会赋值,但是static变量是类的属性,在类被首次加载的时候就已经被赋值类,导致spring忽略静态变量。
所以如下这种写法就是错误的,这样是无法注入的,在使用该变量的时候会导致空指针错误:
@Autowired
private static StudentMapper studentMapper;
Spring 依赖注入是依赖set方法,静态变量不属于对象,只属于类。解决方法就是加上非静态的set方法,如下:
private static StudentMapper studentMapper;
public StudentMapper getStudentMapper() {
return studentMapper;
}
@Autowired
public void setStudentMapper(StudentMapper studentMapper) {
this.studentMapper = studentMapper;
}