Spring-Boot @Autowired in main class is getting null

后端 未结 1 1819
名媛妹妹
名媛妹妹 2020-12-10 04:13

I want to connect to a Sonic Broker Topic and Listen for any incoming XML message. I did something like below;

Application.java

@SpringBootApplicatio         


        
相关标签:
1条回答
  • 2020-12-10 04:14

    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...");
        }
    }
    
    0 讨论(0)
提交回复
热议问题