Springboot无法通过自动连接的注释初始化并注入第三方bean

时间:2018-05-10 05:16:35

标签: java spring-boot rabbitmq javabeans

我的配置类有问题。按日志的实际问题是:

> Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-05-10 10:47:47.622 ERROR 10728 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Field queue in com.example.taskgenerator.Sender required a bean of type 'org.springframework.amqp.core.Queue' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.amqp.core.Queue' in your configuration.

我第一次使用带有RabbitMQ的springboot排队服务sdk。

    package com.example.taskgenerator;
    import org.springframework.amqp.core.Queue;
    @Configuration
    public class TaskGeneratorConfig {
        @Bean
        public Queue queue() {
            return new Queue("simple-queue");
        }
    }

queue是Sender类的依赖项。

package com.example.taskgenerator;
import org.springframework.amqp.core.Queue;
@Component
public class Sender {
 @Autowired
    private Queue queue;
}

请帮忙。

编辑:

添加我的主要课程:

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;

@SpringBootApplication
//@EnableScheduling
//@EnableAsync
public class FileDumpReaderApplication {

    @Profile("usage_message")
    @Bean
    public CommandLineRunner usage() {
        return new CommandLineRunner() {

            @Override
            public void run(String... args) throws Exception {
                System.out.println("This app uses Spring profiles to control its behaviour.");
                System.out.println("Sample usage : java -jar readerapp.jar --spring.profiles.active=hello_world,sender");
            }

        };
    }

    @Profile("!usage_message")
    @Bean
    public CommandLineRunner usageTwo() {

        return new AppRunner();
    }

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

命令行运行者类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ConfigurableApplicationContext;

public class AppRunner implements CommandLineRunner {


    @Autowired
    private ConfigurableApplicationContext context;

    @Autowired
    private Sender sender;

    @Override
    public void run(String... args) throws Exception {
            sender.send();

            //context.close();
    }

}

注意:所有类都在同一个包中。

1 个答案:

答案 0 :(得分:0)

扫描您的包裹 -
@SpringBootApplication(scanBasePackages = {“com.example.taskgenerator”})并在AppRunner类上给出注释(@Component)。

您必须扫描您的软件包,以便在应用程序启动时它们成为ApplicationContext的一部分。