Java 尝试@Autowired WorkerThread时出现NullPointerException
我用@SpringBootApplication注释了我的主应用程序。以下是以下各项的代码:Java 尝试@Autowired WorkerThread时出现NullPointerException,java,spring-boot,nullpointerexception,autowired,applicationcontext,Java,Spring Boot,Nullpointerexception,Autowired,Applicationcontext,我用@SpringBootApplication注释了我的主应用程序。以下是以下各项的代码: @SpringBootApplication public class Application { private Logger logger = LoggerFactory.getLogger(Application.class); @Autowired public ExternalConfiguration configurati
@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
您有两个选择:
@postcontract
而不是构造函数中进行初始化很明显,我知道NullPointerException是什么。我说的是ApplicationContext没有得到@Autowired,因此它是空的。请仔细阅读问题。请在访问应用程序上下文期间抛出NPE时提供堆栈跟踪。