Spring-Boot @Autowired in main class is getting null

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...");
    }
}

Leave a Comment