gpt4 book ai didi

java - 为什么在 Spring 应用程序中应避免使用 getBean()

转载 作者:行者123 更新时间:2023-12-02 02:32:34 24 4
gpt4 key购买 nike

我正在浏览 spring 文档,并发现了以下声明 -

You can then use getBean to retrieve instances of your beans. The ApplicationContext interface has a few other methods for retrieving beans, but ideally your application code should never use them. Indeed, your application code should have no calls to the getBean() method at all, and thus no dependency on Spring APIs at all. For example, Spring’s integration with web frameworks provides dependency injection for various web framework components such as controllers and JSF-managed beans, allowing you to declare a dependency on a specific bean through metadata (e.g. an autowiring annotation).

引用-https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html

在我的应用程序中,我收到客户端方法的一些参数,根据这些参数,我注入(inject)接口(interface)的正确实现。我的方法是,在连接这些参数后搜索 bean id。例如,如果我收到 type=CsubType=D,我会通过调用 getBean(beanId) 获取带有 bean id=typeCsubTypeD 的 bean 。即我的依赖关系是由运行时决定的。

我已经浏览过Why is Spring's ApplicationContext.getBean considered bad?

但是,这并不涵盖我的用例(该问题中的评论也提到了这一点)。

最佳答案

一般来说,我的建议是避免对当月 flavor 的狂热追捧。

如今,控制反转已经成为一种炒作(作为 SOLID 设计原则的一部分),因此如果有人使用任何违反该原则的东西,人们会盲目地抨击它并说你应该避免使用它。然而,真正的答案是,软件设计并不存在普遍规律。如果您有正当理由不在应用程序中使用控制反转,那么您肯定可以使用 getBean()。该原则通常意味着的意思是“不要在静态初始化上下文中使用getBean(),您可以在其中使用控制反转”。

例如,我们有一个应用程序,它使用 Spring 作为“bean 脚本语言”,允许非开发人员定义可配置的 Java bean,而无需使用成熟的 DSL。如果您在这方面使用 Spring,那么没有合理的方法可以避免使用 getBean()

关于java - 为什么在 Spring 应用程序中应避免使用 getBean(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46857314/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com