Description
At times users can get into scenarios where they are getting circular dependencies and it is due to how they have structured their configuration.
For example, the following will fail due to circular bean dependencies:
@Component
class MyFilter {
MyFilter(MyDependency dependency) {}
}
@Configuration
class MyConfig {
MyFilter myFilter;
MyConfig(MyFilter myFilter) {
this.myFilter = myFilter;
}
@Bean
MyOther myOther() {
return new MyOther(this.myFilter);
}
@Bean
MyDependency myDependency() {
return new MyDependency();
}
}
The reason this will fail is because MyConfig
requires MyFilter
, but MyFilter
requires MyDependency
which is provided by MyConfig
. Spring cannot resolve MyDependency
because it is unable to create an instance of MyConfig
without MyFilter
. Spring has the same problem if autowiring member variables because it does not know if the member variable is required for instantiating Beans defined in non-static methods.
There are a few ways of minimizing circular dependencies that I'm aware of:
- Splitting up the Configuration into more classes (can be difficult with large object graphs)
- Using static methods for Bean declarations
- Using arguments to the method of the bean definition instead of member variables in Configuration classes
To me the best option is to use method arguments for resolving dependencies is the best option because it provides the most precise definition of the dependency graph.
I think it would be good if Spring documented some of the tradeoffs and benefits of how to use @Configuration
. At minimum, I believe it would be beneficial to add something stating that using arguments to the methods to define Bean methods can solve many circular dependencies problems.