简体   繁体   English

什么时候在 Spring Boot 中执行带有 @Bean 注释的方法?

[英]When are methods annotated with @Bean are excuted in Spring Boot?

I'am reading the springboot tutorial on how to consume a rest service and there is the main class我正在阅读关于如何使用 rest 服务的 springboot 教程,主要是 class

@SpringBootApplication
public class ConsumingRestApplication {
    private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);

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

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
        return args -> {
            Quote quote = restTemplate.getForObject(
                    "https://quoters.apps.pcfone.io/api/random", Quote.class);
            log.info(quote.toString());
        };
    }
}

Now iam new to the Spring (boot) world and the whole IoC - Thing.现在我是 Spring(引导)世界和整个 IoC 的新手。 In a traditional main class I would call the methods run and restTemplate directly or request them via the application context.在传统的主要 class 中,我会直接调用方法runrestTemplate或通过应用程序上下文请求它们。 Here, however, neither of these happens.然而,在这里,这些都没有发生。 How do I know when they are called and in what order they are called?我如何知道它们何时被调用以及它们被调用的顺序是什么? and how are they populated with the parameters values?以及它们是如何填充参数值的?

It used to be called spring magic back then.那时它被称为 spring 魔法。

But you can always search and understand a bit more of how spring works under the hood.但是您总是可以搜索并了解更多关于 spring 是如何工作的。

Spring has multiple classes that search and use complex algorithms to be able to organize and property set up the application context. Spring 具有多个类,这些类可以搜索和使用复杂的算法,以便能够组织和属性设置应用程序上下文。

But for the simple example that you have here:但是对于您在这里的简单示例:

@Bean
public CommandLineRunner run(RestTemplate restTemplate)

The above bean requires as parameter the RestTemplate .上面的 bean 需要RestTemplate作为参数。

So Spring will understand it and execute first the:所以 Spring 会理解它并首先执行:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

in order to create the Rest template and then it could execute the first @Bean as well to create the CommandLineRunner bean.为了创建 Rest 模板,然后它可以执行第一个@Bean以及创建CommandLineRunner bean。

But all of those beans would be correctly set up in the application context only after the run method has been invoked on spring.但是只有在 spring 上调用run方法后,所有这些 bean 才能在应用程序上下文中正确设置。

 public static void main(String[] args) {

        //some code (Beans not ready yet)

        SpringApplication.run(ConsumingRestApplication.class, args);

        //some code (Beans are ready)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM