Why is Spring's ApplicationContext.getBean considered bad?

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

    The idea is that you rely on dependency injection (inversion of control, or IoC). That is, your components are configured with the components they need. These dependencies are injected (via the constructor or setters) - you don't get then yourself.

    ApplicationContext.getBean() requires you to name a bean explicitly within your component. Instead, by using IoC, your configuration can determine what component will be used.

    This allows you to rewire your application with different component implementations easily, or configure objects for testing in a straightforward fashion by providing mocked variants (e.g. a mocked DAO so you don't hit a database during testing)

提交回复
热议问题