brain storm
brain storm

Reputation: 31252

what is the order of bean loading if I have multiple configuration files in spring?

I have three configuration files in spring application.

@Configuration
public class FooConfig { ... }

@Configuration
public class BarConfig { ... }

@Configuration
public class FooBarConfig { ... }

what is the order in which the beans are loaded? can I use a bean defined in FooConfig in BarConfig and vice versa?

EDIT

This works fine as is. But my doubt is whether it works because of chance. There is an ambiguity here since different configuration files are used and the order in which they are resolved is important for proper bean loading.

Upvotes: 5

Views: 10881

Answers (1)

Rafik BELDI
Rafik BELDI

Reputation: 4158

Please have a look at spring documentation

You can use Dependency injection @Autowired to refer to beans declared on other java configuration classes but still it can be ambiguous to determine where exactly the autowired bean definitions are declared and the solution for that is to use @Import

@Configuration
@Import({FooConfig.class, FooBarConfig .class})
public class FooBarConfig { 
//use Autowire to import bean declared in both FooConfig and FooBarConfig
 }

Edit: As for the order if bean A depends on bean B, you are guaranteed that B will be instantiated before A,if there is no dependendy-injection to maitain that order a trick or a workaround is to inject an unused dependency using @Resource.

Upvotes: 5

Related Questions