Home > Software design >  When are methods annotated with @Bean are excuted in Spring Boot?
When are methods annotated with @Bean are excuted in Spring Boot?

Time:08-18

I'am reading the springboot tutorial on how to consume a rest service and there is the main 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. In a traditional main class I would call the methods run and restTemplate directly or request them via the application context. 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?

CodePudding user response:

It used to be called spring magic back then.

But you can always search and understand a bit more of how spring works under the hood.

Spring has multiple classes that search and use complex algorithms to be able to organize and property set up the application context.

But for the simple example that you have here:

@Bean
public CommandLineRunner run(RestTemplate restTemplate)

The above bean requires as parameter the RestTemplate.

So Spring will understand it and execute first the:

@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.

But all of those beans would be correctly set up in the application context only after the run method has been invoked on spring.

 public static void main(String[] args) {

        //some code (Beans not ready yet)

        SpringApplication.run(ConsumingRestApplication.class, args);

        //some code (Beans are ready)
    }
  • Related