尝试 @Autowired WorkerThread 时出现 NullPointerException

NullPointerException when trying to @Autowired WorkerThread

我的主应用程序用@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。

请帮助我。

你的问题是你在此处的构造函数中使用了自动装配字段:

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

spring 在能够注入这些依赖项之前调用了构造函数。所以都是null.

您有两个选择:

  1. @PostContruct 而不是构造函数中进行初始化。
  2. 使用构造函数注入(无论如何这是一个好习惯)