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();
    }
}
posted @ 2020-01-19 13:31  Stars-one  阅读(1375)  评论(0编辑  收藏  举报