1. 业务需求
业务开发中,经常会在工具类中通过mybatis的mapper或者service接口操作数据库,但是工具类中的方法我们一般采用静态static方式,而Mapper或者service接口为非静态方法,所以会存在冲突,静态方法不能调用非静态方法。
2. 问题描述
1.直接使用静态方法调用mapper直接爆红变异不通过提示异常:
Non-static field 'categoryMapper' cannot be referenced from a static context.
2.使用非静态方法调用mapper,编译通过,但是调用异常:java.lang.NullPointerException: null
发现注入为null,其实并不是,只是被static方法“清空”了。
3. 解决方案
直接使用静态方法调用mapper
1.为该类添加注解@Component,将其加载到spring容器中;
2.将该类定义为静态属性,private static CommonUtils commonUtils;
3.添加初始化方法,并为初始化方法添加注解@PostConstruct 注解作用是会在类加在是执行init方法
@PostConstruct
public void init() {
commonUtils = this;
commonUtils.categoryMapper = this.categoryMapper;
}
4.通过该静态属性调用mapper接口,使用 commonUtils.categoryMapper.selectAll();
4. 相关代码
/**
* 静态工具类
*
* @author zrj
* @since 2021/7/29
**/
// 第一步,注入
@Component
public class CommonUtils {
// 第二步,定义静态属性
private static CommonUtils commonUtils;
@Resource
private CategoryMapper categoryMapper;
// 第三步,初始化构造方法
@PostConstruct
public void init() {
commonUtils = this;
commonUtils.categoryMapper = this.categoryMapper;
}
/**
* 1.直接使用静态方法调用mapper直接爆红变异不通过提示异常:
* Non-static field 'categoryMapper' cannot be referenced from a static context
*/
public static void getMapperStatic() {
//categoryMapper.selectAll();
}
/**
* 2.使用非静态方法调用mapper,编译通过,但是调用异常:java.lang.NullPointerException: null
* 发现注入为null,其实并不是,只是被static方法“清空”了。
*/
public void getMapperNoStatic() {
List<Category> categoryList = categoryMapper.selectAll();
System.out.println(categoryList);
}
/**
* 3.直接使用静态方法调用mapper
* 1)为该类添加注解@Component,将其加载到spring容器中;
* 2)将该类定义为静态属性,private static CommonUtils commonUtils;
* 3)添加初始化方法,并为初始化方法添加注解@PostConstruct 注解作用是会在类加在是执行init方法
* @ PostConstruct
* public void init() {
* commonUtils = this;
* commonUtils.categoryMapper = this.categoryMapper;
* }
* 4)通过该静态属性调用mapper接口,使用 commonUtils.categoryMapper.selectAll();
*/
public static void getMapperInitStatic() {
// 第四步,调用
List<Category> categoryList = commonUtils.categoryMapper.selectAll();
System.out.println(categoryList);
}
}