Web User
Web User

Reputation: 7736

Spring Boot could not autowire and run

I am unable to run the attached Spring Boot sampler application. It has an AMQP starter, requiring RabbitMQ. Fundamentally, it is a simple application that just sends a message to a RabbitMQ Exchange with a queue bound to it. I get the following error:

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.company.messaging.MessageDeliveryManager com.company.exec.Application.messageDeliveryManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.company.messaging.MessageDeliveryManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:
 {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Application.java

package com.company.exec;

@SpringBootApplication
public class Application implements CommandLineRunner {

  @Autowired
  MessageDeliveryManager messageDeliveryManager;

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  public void run(String... args) throws Exception {
    messageDeliveryManager.sendMessage(String message);
  }
}

MessageDeliveryManager.java

package com.company.messaging;

public interface MessageDeliveryManager {
  void sendMessage(String message);
}

MessageDeliveryImpl.java

package com.company.messaging;

public class MessageDeliveryManagerImpl implements MessageDeliveryManager {

  @Value("${app.exchangeName}")
  String exchangeName;

  @Value("${app.queueName}")
  String queueName;

  @Autowired
  RabbitTemplate rabbitTemplate;

  @Bean
  Queue queue() {
    return new Queue(queueName, false);
  }

  @Bean
  DirectExchange exchange() {
    return new DirectExchange(exchangeName);
  }

  @Bean
  Binding binding(Queue queue, DirectExchange exchange) {
    return BindingBuilder.bind(queue).to(exchange).with(queueName);
  }

  public void sendMessage(String message) {
    rabbitTemplate.send(queueName, message);
  }
}

I would really appreciate if someone can review and provide a suggestion on what I am doing wrong.

Upvotes: 2

Views: 11907

Answers (1)

Artem Bilan
Artem Bilan

Reputation: 121177

Since you have a package tree like this:

com.company.exec
com.company.messaging

and just use a default @SpringBootApplication, it just doesn't see your MessageDeliveryManager and its implementation. That's because @ComponentScan (the meta-annotation on the @SpringBootApplication) does a scan only for the current package and its subpackages.

To make it worked you should add this:

@SpringBootApplication
@ComponentScan("com.company")

Or just move your Application to the root package - com.company.

Upvotes: 14

Related Questions