Why is Spring's ApplicationContext.getBean considered bad?

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

    I've only found two situations where getBean() was required:

    Others have mentioned using getBean() in main() to fetch the "main" bean for a standalone program.

    Another use I have made of getBean() are in situations where an interactive user configuration determines the bean makeup for a particular situation. So that, for instance, part of the boot system loops through a database table using getBean() with a scope='prototype' bean definition and then setting additional properties. Presumably, there is a UI that adjusts the database table that would be friendlier than attempting to (re)write the application context XML.

    0 讨论(0)
  • 2020-11-22 15:31

    You should to use: ConfigurableApplicationContext instead of for ApplicationContext

    0 讨论(0)
提交回复
热议问题