本文共 510 字,大约阅读时间需要 1 分钟。
Spring无法直接给静态变量注入值,因为静态变量不属于对象,只属于类,也就是说在类被加载字节码的时候变量已经初始化了,也就是给该变量分配内存了,导致spring忽略静态变量。所以如下这种写法就是错误的,这样是无法注入的,在使用该变量的时候会导致空指针错误:
@Autowiredprivate static StudentMapper studentMapper;
Spring 依赖注入是依赖set方法,静态变量不属于对象,只属于类。解决方法就是加上非静态的set方法,如下:
private static StudentMapper studentMapper;public StudentMapper getStudentMapper() { return studentMapper;}@Autowiredpublic void setStudentMapper(StudentMapper studentMapper) { this.studentMapper = studentMapper;}
转载于:https://blog.51cto.com/zero01/2108079