1
votes

Is there any default bean initialization order implicitly in a Spring Boot application? I came across this question in one of my Spring Boot applications when trying to use @ConditionalOnBean annotation.

At first, I thought that Spring does not guarantee any Bean creation order when it's loading beans in @Configuration class or when it's doing component-scan to auto register @Component/@Service/.. classes.

But later, I noticed that in the Spring documentation, it mentions that,

Auto-configuration classes are guaranteed to load after any user-defined bean definitions have been added.

This somehow makes me confused,
1. What counts user defined bean and what counts auto-configuration classes? Specifically, is there any loading order between @Bean in @Configuration class and @Component/@Service directly on class level.
2. If a bean A needs dependency injection of bean B, will B always be initialized first?
3. If @Import is used for configuration aggregation in a Spring Boot application, will beans defined in the imported configuration class being initialized before component-scanned bean registration.

@Component
public class A {}

@Component
public class B {
    @Autowired
    private A a;
}

@Configuration
public class externalConfig {
    @Bean
    public C c() {
        return new C();
    }
}

@SpringBootApplication
@Import(externalConfig.class)
public class testApplication {
    @Bean
    public D d() {
        return new D();
    }
}

When comes to the above code example, my question becomes the following.
1. Without @Import, will C or D always be initialized before A and B?
2. Will B always be initialized before A?
3. With @Import, will C always be initialized first, like even before D?

1

1 Answers

0
votes

Not 100% sure, but:

  1. No there is no guarantee.
  2. A will be initialized, then B, cause you're injecting A.
  3. Import is not guaranteeing the order, only if you have some not lazy injections

Check the DependsOn annotation (enter link description here).

I hope it helps you,