Why is Spring's ApplicationContext.getBean Considered Bad?
Spring's ApplicationContext.getBean() method may seem like a convenient way to access beans, but it is generally considered poor practice. Instead, the preferred approach is to embrace the concept of Inversion of Control (IoC) by using dependency injection.
Delegating Dependency Injection
Calling ApplicationContext.getBean() violates the IoC principle by introducing a dependency on Spring within the consuming class. This makes the class less flexible and harder to test. It also hinders the ability to change the dependency implementation easily.
Benefits of Dependency Injection
Dependency injection offers numerous advantages:
Implementing Dependency Injection in Spring
Instead of invoking ApplicationContext.getBean(), you should declare a method in the consuming class to receive the dependency as an argument. Spring will automatically inject the appropriate dependency based on the bean configuration.
Sample Configuration
<bean>
Bootstrapping
In the main method, retrieve the root bean "myApplication" using ApplicationContext.getBean("myApplication"). This root bean should have dependencies on all other services, eliminating the need for getBean() calls elsewhere.
Conclusion
Avoiding ApplicationContext.getBean() promotes true IoC in Spring, resulting in flexible, testable, and maintainable code. Embracing dependency injection through method arguments allows Spring to perform its designated role of managing dependencies.
The above is the detailed content of Is Using Spring\'s ApplicationContext.getBean() Considered an Anti-Pattern?. For more information, please follow other related articles on the PHP Chinese website!