zoukankan      html  css  js  c++  java
  • spring boot 自动装载对象为null问题的解决

    情况描述

    有个Server类,成员变量是spring中自动管理的bean类对象

    public class Server {
        @Autowired
        private CommandMapper commandMapper;
        @Autowired
        private DevicesMapper devicesMapper;
    	...
    

    原本我是打算在spring boot运行过程中,后台自动开启这个服务(在application类中的main方法中开启)

    public class NongyeApplication {
    
        /*@Autowired
        private static CommandMapper commandMapper;
    
        @Autowired
        private static DevicesMapper devicesMapper;*/
    
        public static void main(String[] args) {
    
            SpringApplication.run(NongyeApplication.class, args);
            new Server().start();
        }
    
    }
    

    但是测试过程中,发现Server类中的那些自动装载的bean类对象为null,原因是因为我使用了new关键字类创建对象

    解决方法

    spring boot中,有个接口ApplicationRunner,当spring boot应用启动完毕之后会回调此接口,可以使用此接口自动完成某些任务。

    所以,我们想要开启服务的话,可以实现此接口。
    我们得把Server类标记注解@Server

    @Service
    public class Server {
        @Autowired
        private CommandMapper commandMapper;
        @Autowired
        private DevicesMapper devicesMapper;
    	...
    

    之后写一个类,去实现ApplicationRunner接口,这样便成功解决了。

    @Component
    public class TcpService implements ApplicationRunner {
        @Autowired
        private Server server;
    
        @Override
        public void run(ApplicationArguments args) throws Exception {
            server.start();
        }
    }
    
  • 相关阅读:
    内存分析利器purify简介
    ldd 的一个安全问题
    Purify检测的代码错误类型
    Purify命令大全
    用GDB调试程序(三)
    寒假Day5:蓝桥杯模拟赛
    寒假Day1:莫队算法+暴力分块
    HDU4578Transformation线段树的加、乘、变、次方操作
    二叉树的相关知识点
    CodeForces 841BGodsend思维
  • 原文地址:https://www.cnblogs.com/stars-one/p/12213338.html
Copyright © 2011-2022 走看看