Why is Spring's ApplicationContext.getBean considered bad?

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

    Using @Autowired or ApplicationContext.getBean() is really the same thing. In both ways you get the bean that is configured in your context and in both ways your code depends on spring. The only thing you should avoid is instantiating your ApplicationContext. Do this only once! In other words, a line like

    ApplicationContext context = new ClassPathXmlApplicationContext("AppContext.xml");
    

    should only be used once in your application.

提交回复
热议问题