当前位置: 代码迷 >> 综合 >> autowired 注解失败报错为java.lang.NullPointerException空指针异常
  详细解决方案

autowired 注解失败报错为java.lang.NullPointerException空指针异常

热度:72   发布时间:2023-09-19 14:58:25.0

网上找了半天,才发现解决办法。很怪异的解决方式、

通过添加以下三个关键的地方,可以解决该问题(@PostConstruct:被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,类似于Serclet的inti()方法。被@PostConstruct修饰的方法会在构造函数之后,init()方法之前运行。):

@Component  //关键一
public class ReceiveProgress implements Progress {   @Autowiredprivate DataRecieveRecordMapper dataRecieveRecordMapper;@Autowiredprivate DataRecieveDataMapper dataRecieveDataMapper;@Autowiredprivate DispatchFlowsMapper dispatchFlowsMapper;private static ReceiveProgress receiveProgress;//关键二@PostConstruct //关键三public void init(){receiveProgress = this;receiveProgress.dataRecieveRecordMapper = this.dataRecieveRecordMapper;receiveProgress.dataRecieveDataMapper = this.dataRecieveDataMapper;receiveProgress.dispatchFlowsMapper = this.dispatchFlowsMapper;}
...//使用的时候这样使用
receiveProgress.dataRecieveRecordMapper.insertSelective(dataRecieveRecord);

 

需要注意:注入类的调用方法是

receiveProgress.dataRecieveRecordMapper.insertSelective(dataRecieveRecord);

这样就可以正常使用了。

  相关解决方案