Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
brain storm Avatar asked May 13 '15 17:05

brain storm


Video Answer


1 Answers

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.

like image 104
Rafik BELDI Avatar answered Oct 15 '22 18:10

Rafik BELDI