30,000
社区成员
发帖
与我相关
我的任务
分享
public class HandleGPSInfoHexian extends Thread{
@Autowired
private KafkaTemplate<String, Object> kafkaTemplate;
@Override
public void run() {
System.out.println("1");
kafkaTemplate.send("test1", "1");
}
}
kafkaTemplate显示null。
this.kafkaTemplate = (KafkaTemplate) SpringContextUtils.getObject(KafkaTemplate.class);
使用这个方法已解决。
springBoot中在多线程中为了线程安全,一般都是防止注解注入的,新线程中@Autowired注解无法注入需要的bean(即:保存历史数据的service层),程序一直在报 NullPointerException ,所以需要调用spring中的ApplicationContext来获取封装的bean。
解决可以写一个工具类来获取spring中的bean