spring controller层引用service报空指针异常nullpointExceptio问题

 更新时间:2022年2月28日 10:21  点击:651 作者:lileLife

调用controller报空指针有两种情况 

  • 1、 service 或者mapper 没有加载到spring容器中 ,引用时候肯定报空指针
  • 2、 service加载到spring容器中了, 但是controller中定义的方法为private,私有方法被接口访问时候,因为private作用域的问题,无法获取该方法,报空指针

没有加载到spring容器中

1、controller层中的service没有注入,(@Resource @Autowired)

2、service层没有使用@Service修饰  

3、Application启动类中,没有使用定义需要加载到容器中的包

该包中包含需要加载进去的各种bean ,使用@ComponentScan是指定需要加载的bean所在包,而@SpringbootApplication其实已经包含了该注解 

4、 常见报空指针的场景是,用户自定义了Util下的类,然后使用@Service引用了定义的Service,但是报空指针。   这种是因为,该Util类,没有加载到Spring容器中,需要使用@Component注解 ,同时,这个util类需要使用@Resource引用到Spring容器中,这样该util类和service才会一同作用到Spring容器中。

 controller层使用@RestController注释,在启动时候会因为@componentScan的原因,加载进容器中,总结一点,要使用该bean,该bean需加载进Spring容器中。

Controller类下的方法private私有了

这种是引用java 修饰符作用域的问题,private修饰的方法只能在该类中使用。  

其实你使用Idea时候,在controller中定义private方法时候, 编辑器会显示

Idea已经告诉你,这种的话没有被引用,

而将方法public后:服务启动后, 该处会显示正常不会报灰色   

插一句:idea是真的牛皮的编辑器 

controller层引用service层报空指针问题

应用service层时

private Manager manager;

少加了@Autowired

添加后,空指针报错解决

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

原文出处:https://blog.csdn.net/lileLife/article/details/80699654

[!--infotagslink--]

相关文章