记一次测试rabiitmq ‘org.springframework.amqp.core.AmqpAdmin‘ that could not be found. 解决
rabiitmq ‘org.springframework.amqp.core.AmqpAdmin‘ that could not be found
1. 首先呢这是因为AmqpAdmin,没找到;和没有导入依赖无关,
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
</dependency>
因为,这里面直接包好了这个引用,只要导入这个就好
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
3. 那是什么原因导致这个扫不到呢?
一开始提示测试类没有上下文环境
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
然后我傻傻的直接在,测试类上把测试类加进去了,然后还是找不到上下文,可能大家到这里估计已经知道为什么会报这个错了,主启动类都写错了,怎么可能找到上下文嘛(被自己蠢了)
@SpringBootTest(classes = testApplicationTests.class)
5. 然后借助GPT 分析,得到一下启示
如果您的应用程序主要配置类的名称为YourApplication,则可以在测试类上使用注释 @SpringBootTest(classes = YourApplication.class)。这将为测试创建完整的Spring上下文,并使其能够正常运行。您需要将 "YourApplication" 替换为您自己应用程序中的主要配置类。
然后把测试类的注解改成下面这样,测试成功跑起来了;
@SpringBootTest(classes = testApplication.class)
6. 附上测试案例代码(代码是谷粒商城的案例啦)
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
class TestApplicationTests {
@Resource
AmqpAdmin amqpAdmin;
@Resource
RabbitTemplate rabbitTemplate;
@Test
public void sendMessageTest() {
OrderReturnReasonEntity reasonEntity = new OrderReturnReasonEntity();
reasonEntity.setId(1L);
reasonEntity.setCreateTime(new Date());
reasonEntity.setName("哈哈");
//发送消息
String msg = "hello Wrold";
rabbitTemplate.convertAndSend("hello-java-exchange","hello.java",reasonEntity);
log.info("消息发送完成");
}
/**
* 1、如果创建Exchange Queue Binding
*/
@Test
public void contextLoads() {
//amq
// DirectExchange(String name, boolean durable, boolean autoDelete, Map<String, Object> arguments) {
DirectExchange directExchange = new DirectExchange("hello-java-exchange",true,false);
amqpAdmin.declareExchange(directExchange);
log.info("Exchange[{}]创建成功","hello-java-exchange");
}
@Test
public void createQueue() {
//public Queue(String name, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments) {
Queue queue = new Queue("hello-java-queue",true,false,false);
amqpAdmin.declareQueue(queue);
log.info("Queue[{}]创建成功","hello-java-queue");
}
@Test
public void createBinding() {
//public Binding(String destination,目的地
// DestinationType destinationType,目的地类型
// String exchange,交换机
// String routingKey, 路由key
//map<String,Object> arguments 自定义参数
Binding binding = new Binding("hello-java-queue",
Binding.DestinationType.QUEUE,
"hello-java-exchange",
"hello.java",null);
amqpAdmin.declareBinding(binding);
log.info("Binding[{}]创建成功","hello-java-binding");
}
}
别忘了导入依赖!
7. 总结:
一、 因为引用了错误的上下文,导致allication.yml里面的配置,设置失败,从而导致rabbtimq注入容器失败,然后导rabiitmq ‘org.springframework.amqp.core.AmqpAdmin‘ that could not be found。
8. 学习千万要细心,不然又是坐牢的几个小时,害..
更多推荐
所有评论(0)