问题:
工具类:
@Component
public class RabbitMqUtil {
@Autowired
private RabbitTemplate rabbitTemplate;
//注意,若是没有创建该队列,并且没有消费者对其消费,则会创建失败的
public void helloProvider(String routingKey, String o) {
rabbitTemplate.convertAndSend(routingKey, o);
}
}
使用:
@SpringBootTest
@RunWith(SpringRunner.class)
class ApplicationTests {
@Test
public void test(){
RabbitMqUtil rabbitMqUtil= new RabbitMqUtil()
rabbitMqUtil.helloProvider("hello","我好爱你");
}
}
结果: 空指针异常
解决:
spring中kill掉了大部分的new,所以应该使用注入的方法来调用它
@SpringBootTest
@RunWith(SpringRunner.class)
class ApplicationTests {
@Autowired
private RabbitMqUtil rabbitMqUtil;
@Test
public void test(){
rabbitMqUtil.helloProvider("hello","我好爱你");
}
}