尝试@Autowired WorkerThread

时间:2016-08-26 06:47:09

标签: java spring-boot nullpointerexception autowired applicationcontext

我的主应用程序使用@SpringBootApplication注释。以下是以下代码:

    @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);
        }
    }

这是我的 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();
    }
}

我尝试调试并发现我的 ApplicationContext 没有获得自动连接并且为空。

我没有使用 new 来实例化WorkerThread。

请帮帮我。

1 个答案:

答案 0 :(得分:1)

您的问题是您在构造函数中使用自动装配的字段:

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

构造函数在Spring能够注入这些依赖项之前被spring调用。因此,它们都是null

您有两种选择:

  1. @PostContruct而不是构造函数中进行初始化。
  2. 使用构造函数注入(无论如何都是好的做法)