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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With