为什么 Spring 即使 Bean 具有 @Component 注释也不创建它?

Why doesn't Spring create a Bean even tho it has a @Component annotation?

我猜这个问题已经被问过很多次了,但我没有从这些线程中找到解决我的问题的方法。

我收到此错误,我无法解释原因。


应用程序启动失败


描述:

com.ll.rabbittutorial.messagingconsumer.MessagingconsumerApplication 中方法 listenerAdapter 的参数 0 需要找不到类型 'com.ll.rabbittutorial.messagingconsumer.RoomCleanerProcessor' 的 bean。

操作:

考虑在您的配置中定义类型为 'com.ll.rabbittutorial.messagingconsumer.RoomCleanerProcessor' 的 bean。

我猜这是 class 导致错误的原因

@Component
public class RoomCleanerProcessor {


    private final ObjectMapper objectMapper;

    private static final Logger logger = LoggerFactory.getLogger(RoomCleanerProcessor.class);

    @Autowired
    public RoomCleanerProcessor(ObjectMapper objectMapper)
    {
        super();
        this.objectMapper=objectMapper;
    }

    public void receiveMessage(String roomJson){
        logger.info("Message received");
        try{
            Room room = this.objectMapper.readValue(roomJson, Room.class);
            logger.info("Room ready for cleaning "+room.getNumber());
        } catch (IOException e) {
            logger.error("Exception caught", e);

        }
    }
}

首先,同样的错误发生在我试图注入的 ObjectMapper 对象上。但在应用程序中使用@ComponentScan 注释后 class,问题消失了。

@SpringBootApplication
@ComponentScan({"com.ll.rabbittutorial.messagingconsumer.RoomCleanerProcessor"})
public class MessagingconsumerApplication {

    @Value("$amqp.queue.name}")
    private String queueName;

    @Value("${amqp.exchange.name}")
    private String exchangeName;

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

    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange(exchangeName);
    }

    @Bean
    public Binding binding(Queue queue, TopicExchange topicExchange){
        return BindingBuilder.bind(queue).to(topicExchange).with(queueName);
    }

    @Bean
    public MessageListenerAdapter listenerAdapter(RoomCleanerProcessor roomCleanerProcessor){
        return new MessageListenerAdapter(roomCleanerProcessor, "receiveMessage");

    }
    @Bean
    public SimpleMessageListenerContainer container(ConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        return container;
    }

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

}

我想我也可以通过对应用程序进行组件扫描来解决这个问题class,但它没有帮助。我该如何解决这个问题?

@ComponentScan 值应该包括包,而不是 类。 此外,@SpringBootApplication 封装了@Configuration、@EnableAutoConfiguration 和@ComponentScan 注释及其默认属性。

@ComponentScan 的默认值是没有参数。没有参数,它告诉 Spring 扫描当前包及其所有子包。因此,如果您将 MessagingconsumerApplication 放在 RoomCleanerProcessor 的父包中,它应该可以工作。