-2

I have my main Application annotated with @SpringBootApplication. Here is the code for the following:

    @SpringBootApplication
    public class Application {

        private Logger logger = LoggerFactory.getLogger(Application.class);

        @Autowired
        public ExternalConfiguration configuration;

        @Autowired
        WorkerThread workerThread;

        public static void main(String[] args) {
            SpringApplication springApplication = new SpringApplication(new Object[] { Application.class });
            springApplication.run(args);
        }
    }

And here is my WorkerThread.java

@Component
@Scope("prototype")
public class WorkerThread implements Runnable {
    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    ExternalConfiguration externalConfiguration;

    @Autowired
    WorkerConfig workerConfig;

    WorkerQueueDispatcher dispatcher;

    public WorkerThread() {
        dispatcher = applicationContext.getBean(WorkerQueueDispatcher.class, externalConfiguration.getEventQ(),
                workerConfig.getWorkers());
    }

    @Override
    public void run() {
        logger.info("Worker thread started. Thread ID :" + Thread.currentThread().getId());
        dispatcher.run();
    }
}

I tried debugging and found out that my ApplicationContext was not getting Autowired and is null.

I haven't used new for instantiating the WorkerThread.

Please help me.

amitection
  • 2,696
  • 8
  • 25
  • 46
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – xenteros Aug 26 '16 at 07:00
  • Obviously I know what a NullPointerException is. I am talking about ApplicationContext not getting @Autowired and hence it is null. Please read the question carefully. – amitection Aug 26 '16 at 07:06
  • Please provide stack trace when NPE is thrown during accessing application context. – Marek J Aug 26 '16 at 07:26

1 Answers1

1

Your problem is that you are using autowired fields in constructor here:

    public WorkerThread() {
        dispatcher = applicationContext.getBean(WorkerQueueDispatcher.class, externalConfiguration.getEventQ(),
            workerConfig.getWorkers());
    }

Constructor is called by spring before it is able to inject these dependencies. Therefore they are all null.

You have two options:

  1. Do your initialization in @PostContruct instead of constructor.
  2. Use constructor injection (it is good practice anyways)
luboskrnac
  • 23,973
  • 10
  • 81
  • 92