新关键字在 Spring 框架中的作用

Role of new keyword in Spring Framework

在Spring框架中,似乎beans are the preferred way of creating objects可以用于业务逻辑。

[Dependency injection] is a process whereby objects define their dependencies, that is, the other objects they work with, only through constructor arguments, arguments to a factory method, or properties that are set on the object instance after it is constructed or returned from a factory method. The container then injects those dependencies when it creates the bean. This process is fundamentally the inverse, hence the name Inversion of Control (IoC), of the bean itself controlling the instantiation or location of its dependencies by using direct construction of classes, or a mechanism such as the Service Locator pattern.

所以根据我的简单理解,区别是这样的:

// Plain ol' Java
Foo f = new Foo();

// Using beans in Spring Framework
Foo f = FooFactory.get();

作为规则,在 @Configuration 类 和 @Bean 定义之外的方法中,开发人员应该只使用 bean 获取对象,这是否过于简单化了?具体来说,在我想要一个新对象的情况下,我应该注入一个原型 bean 而不是直接使用 new 关键字吗?

下面显示了一个我不确定是否遵循 Spring 约定的代码示例。

// Construct a new object that will be created in the database
RecordDto record = new RecordDto();

// Or should I be using some bean factory?
RecordDto record = RecordDtoFactory.get();

请阅读来自亲爱的马丁·福勒的 this Article。 我认为当您的应用程序中的某些组件依赖于其他组件来完成某些功能时,IOC 概念很有用。 IoC 容器将负责管理软件组件的创建和生命周期,并将它们注入依赖组件,而不是手动访问这些组件实例。

例如,当某些服务需要 DAO 的实例时,它将从容器中获取它而不是创建它。

但在 DTO 的情况下,它们将只保存数据,这不是真正的依赖。所以我认为在这种情况下使用 "new" 更好。