写在开始
起因是项目需要启动一个多线程服务往RabbitMq灌入数据,当启动多线程以@Autowired注解形式注入RabbitMq服务时发现NPE(空指针异常)。
首先排查RabbitMq是否注入成功,结果在Application中成功注入RabbitMq。调查后发现多线程类是无法通过注解方式直接获取容器中内容的,
方案
将Application中获取的句柄放入线程的构造函数中,搞定~~
通过下面两种方案中的一种获取注入到容器中的内容,前提是该项目为spring-boot项目
1注解方式
2应用上下文方式
代码片段
package com.navinfo.platform.rabbitmq; import com.navinfo.platform.rabbitmq.configuration.RabbitMqConfiguration; import com.navinfo.platform.rabbitmq.message.DefaultMessageChannel; import com.navinfo.platform.rabbitmq.message.MessageChannel; import com.navinfo.platform.rabbitmq.thread.PushToRabbitMQThread; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Import; import javax.annotation.PostConstruct; @SpringBootApplication @ComponentScan("com.navinfo.platform.rabbitmq") @Import({RabbitMqConfiguration.class}) public class LocationRabbitmqApplication { @Autowired private MessageChannel messageChannel; @Autowired private ApplicationContext applicationContext; public static void main(String[] args) { SpringApplication.run(LocationRabbitmqApplication.class, args); } @PostConstruct public void TestFun() { // 注解方式 new PushToRabbitMQThread(messageChannel).start(); // 应用上下文方式 MessageChannel messageChannel2 = applicationContext.getBean(DefaultMessageChannel.class); new PushToRabbitMQThread(messageChannel2).start(); } }
package com.navinfo.platform.rabbitmq.thread; import com.navinfo.platform.rabbitmq.command.TestCommand; import com.navinfo.platform.rabbitmq.message.MessageChannel; import java.util.UUID; /** * @Description:批量写入数据到RabbitMQ * @Author:tianminghai * @Date:3:15 PM 2018/10/31 */ public class PushToRabbitMQThread extends Thread { private MessageChannel messageChannel; public PushToRabbitMQThread(MessageChannel messageChannel) { this.messageChannel = messageChannel; } @Override public void run() { while (true) { TestCommand testCommand = new TestCommand(); testCommand.setTestKey(UUID.randomUUID().toString()); messageChannel.send("tianmh", testCommand); try { this.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }