Why is Spring's ApplicationContext.getBean considered bad?

前端 未结 14 2033
一整个雨季
一整个雨季 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:27

    The motivation is to write code that doesn't depend explicitly on Spring. That way, if you choose to switch containers, you don't have to rewrite any code.

    Think of the container as something is invisible to your code, magically providing for its needs, without being asked.

    Dependency injection is a counterpoint to the "service locator" pattern. If you are going to lookup dependencies by name, you might as well get rid of the DI container and use something like JNDI.

提交回复
热议问题