通常在静态的方法中使用 Mybatis Mapper, 自动注入 @Autowired 是不行的, 会报空指针异常.
解决办法 :
需要用到 @PostConstruct 注解, 该注解会在类加载之前自动执行标识的方法,在放方法中把静态的类赋值给非静态的类.
示例代码
@Component
public class ApplicationUtil {
@Autowired
private Mapper mapper;
private static StaticMapper staticMapper;
@PostConstruct
public void init(){
this.mapper = staticMapper;
}
public static StaticMapper getStaticMapper(){
return staticMapper;
}
}
调用
public class test{
@Autowired
ApplicationUtil applicationUtil
public void testMapper (){
//从工具类中获取到静态的Mapper
StaticMapper staticMapper = ApplicationUtil.getStaticMapper();
//调用Maper方法
staticMapper.selectOne(....);
}
}