解决静态utils里面注入mapper对象
项目中需要在一个utils工具类中,调用mapper对象来进行功能实现,然而静态方法里面直接注入会报空指针的错误,网上查了一些资料得出如下解决办法
重点步骤:
1,utils类上面添加@Component注解
2,@Autowired注入需要使用的mapper对象,注意不是静态的
3,创建一个静态的这个utils的对象 private static LayoutNumUtils layoutNumUtils;
4,创建一个init方法,添加@PostConstruct注解,方法内容如下
OK,在接下来的调用中,使用utils的对象来调用对应的mapper对象layoutNumUtils.busiTabLayoutMapper.selectByTabId(tabId);
- <span style="font-size:18px;">@Component
- public class LayoutNumUtils {
- @Autowired
- private BusiTabMapper busiTabMapper;
- @Autowired
- private BusiTabLayoutMapper busiTabLayoutMapper;
- private static LayoutNumUtils layoutNumUtils;
- @PostConstruct
- public void init(){
- layoutNumUtils = this;
- layoutNumUtils.busiTabMapper = this.busiTabMapper;
- layoutNumUtils.busiTabLayoutMapper = this.busiTabLayoutMapper;
- }
- public static void layoutTypeCheck(Integer tabId){
- try {
- List<BusiTabLayout> list = layoutNumUtils.busiTabLayoutMapper.selectByTabId(tabId);</span>