今天写了一个工具类,但是要用到Service接口,很自然的就想到了自动注入,但是在运行时报错:空指针。
后来网上搜索发现应该这样:
public class TestUtils {
@Autowired
private ItemService itemService;
@Autowired
private ItemMapper itemMapper;
public static TestUtils testUtils;@PostConstruct
public void init() {
testUtils = this;
}
//utils工具类中使用service和mapper接口的方法例子,用'testUtils.xxx.方法' 就可以了
public static void test(Item record){
testUtils.itemMapper.insert(record);
testUtils.itemService.queryAll();
}
}
希望对你有帮助!
原文连接:请点击!
本文介绍了一种解决工具类中Service接口自动注入的问题方法,通过使用@Autowired和@PostConstruct注解实现非静态成员变量的注入,避免了空指针异常,并提供了具体的代码示例。
139

被折叠的 条评论
为什么被折叠?



