首页 > 编程语言 > 详细

spring boot 自动装载对象为null问题的解决

时间:2020-01-19 14:27:23      阅读:63      评论:0      收藏:0      [点我收藏+]

情况描述

有个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();
    }
}

spring boot 自动装载对象为null问题的解决

原文:https://www.cnblogs.com/stars-one/p/12213338.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!