spring-projects / spring-framework

Spring Framework
https://spring.io/projects/spring-framework
Apache License 2.0
56.46k stars 38.09k forks source link

Document how to optimize the dependency graph #30333

Open rwinch opened 1 year ago

rwinch commented 1 year ago

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:

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.

Related Issues

sbrannen commented 1 year ago

To be addressed in conjunction with:

Ankitbagga75 commented 1 year ago

Hi @sbrannen should New Documentation file be created or There is any existing file where we can add Documentation?