Spring's ApplicationContext.getBean considered bad?

/
0 Comments

 ApplicationContext.getBean() is a method in Spring framework that allows you to retrieve a bean from the Spring application context. The method is considered to be an anti-pattern by some developers because it can lead to tight coupling between the calling code and the Spring context. This tight coupling can make it difficult to test the code in isolation and can also make it harder to change the implementation of the beans in the future.


Here is an example of how ApplicationContext.getBean() can lead to tight coupling:

public class MyService {

  public void doSomething() {

    MyDependency dependency = (MyDependency) ApplicationContext.getBean("myDependency");

    dependency.performTask();

  }

}

In the example above, the MyService class is tightly coupled to the Spring application context, as it directly accesses the ApplicationContext to retrieve a bean. If you want to test MyService, you will have to set up the entire Spring context, which can make the test more complex and harder to write.

A better approach is to use dependency injection to make the dependencies of MyService available. This way, you can easily provide mock implementations of the dependencies for testing, and you can also change the implementation of the dependencies in the future without having to modify the MyService code.

Here is an example of how you can use dependency injection to achieve loose coupling:

public class MyService {
  private MyDependency dependency;

  public MyService(MyDependency dependency) {
    this.dependency = dependency;
  }

  public void doSomething() {
    dependency.performTask();
  }
}
With the code above, you can easily provide a mock implementation of MyDependency for testing and you can change the implementation of MyDependency without having to modify the MyService code.



You may also like

No comments: