Spring-Boot @Autowired in main class is getting null

烈酒焚心 提交于 2019-12-05 03:45:26

onStartup is called by the servlet container very early in your application's lifecycle and is called on an instance of the class that was created by the servlet container, not Spring Boot. This is why jmsTopicListener is null.

Rather than overriding onStartup you could use a method annotated with @PostConstruct. It will be called by Spring once it's created an instance of Application and injected any dependencies:

@SpringBootApplication
@ComponentScan({"com.mainpack", "com.msgpack.jms"})
@EnableJms
public class Application extends SpringBootServletInitializer {

    @Autowired
    private JmsTopicListener jmsTopicListener;

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    @PostConstruct
    public void listen() { 
        jmsTopicListener.listenMessage();
    }

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(Application.class, args);
        LogService.info(Application.class.getName(), "Service Started...");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!