Why is Spring's ApplicationContext.getBean considered bad?

前端 未结 14 1809
一整个雨季
一整个雨季 2020-11-22 14:33

I asked a general Spring question: Auto-cast Spring Beans and had multiple people respond that calling Spring\'s ApplicationContext.getBean() should be avoided

14条回答
  •  北海茫月
    2020-11-22 15:10

    I mentioned this in a comment on the other question, but the whole idea of Inversion of Control is to have none of your classes know or care how they get the objects they depend on. This makes it easy to change what type of implementation of a given dependency you use at any time. It also makes the classes easy to test, as you can provide mock implementations of dependencies. Finally, it makes the classes simpler and more focused on their core responsibility.

    Calling ApplicationContext.getBean() is not Inversion of Control! While it's still easy to change what implemenation is configured for the given bean name, the class now relies directly on Spring to provide that dependency and can't get it any other way. You can't just make your own mock implementation in a test class and pass that to it yourself. This basically defeats Spring's purpose as a dependency injection container.

    Everywhere you want to say:

    MyClass myClass = applicationContext.getBean("myClass");
    

    you should instead, for example, declare a method:

    public void setMyClass(MyClass myClass) {
       this.myClass = myClass;
    }
    

    And then in your configuration:

    ...
    
    
       
    
    

    Spring will then automatically inject myClass into myOtherClass.

    Declare everything in this way, and at the root of it all have something like:

    
       
       
    
    

    MyApplication is the most central class, and depends at least indirectly on every other service in your program. When bootstrapping, in your main method, you can call applicationContext.getBean("myApplication") but you should not need to call getBean() anywhere else!

提交回复
热议问题