Zakariyya / blog

https://zakariyya.github.io/blog/
6 stars 1 forks source link

Springboot @Component下@Autowired的注入为null【转】 #65

Open Zakariyya opened 4 years ago

Zakariyya commented 4 years ago

date: 2018-08-23 16:17:39 原文: SpringBoot在自定义类中调用service层等Spring其他层

自定义类时,出现 @Autowired 下的层出现空指针异常。

背景

做了一个TCP服务器来接入智能设备,然后需要将设备实时发送的定位等关键信息存储到数据库。为了考虑将来可能对外提供rest接口,采用将TCP服务器集成到SpringBoot框架,当然,也是为了能最快利用mybatis框架实现数据访问,然后依次解决了如何启动,如何注销等各种问题,然后在TCP服务器消息处理时,需要写数据库,直接调用DAO层,编译报错。改为调用Service层,编译正常,运行到调用的地方,报空指针异常,跟踪到异常位置,发现service为空,也就是按照之前controller层通过@Autowired注入service层失效。

解决方案

@Component
public class ServerHandler extends IoHandlerAdapter {
    @Autowired
    protected HealthDataService healthDataService;
    private static ServerHandler  serverHandler ;
    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {  
        serverHandler = this;  
        serverHandler.healthDataService = this.healthDataService;        
        // 初使化时将已静态化的testService实例化
    }  
    //测试调用
    public void test(){
        serverHandler .healthDataService.你的service层方法;
        //
    }

说明

那些趟过的坑

刚开始调用的时候,总觉得很简单,以前springmvc写个配置,将对象标注为bean就可以随意调用Spring IOC容器的beans了,但是这是SpringBoot,估计还是有区别,依次试验了百度出来的前三页帮助,基本没有成功的。包括:

以上为原文转载,再次感谢原文作者分享: SpringBoot在自定义类中调用service层等Spring其他层