Role of new keyword in Spring Framework
在Spring框架中,bean似乎是创建要在业务逻辑中使用的对象的首选方法。
[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.
所以从我的简单理解来看,区别是这样的:
1 2 3 4 5 | // Plain ol' Java Foo f = new Foo(); // Using beans in Spring Framework Foo f = FooFactory.get(); |
一般来说,在
下面是一个代码示例,我不确定我是否遵循了Spring约定。
1 2 3 4 5 | // 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(); |
请阅读这篇文章从亲爱的马丁福勒。我认为当应用程序中的某个组件依赖于其他组件以完成某些功能时,IOC概念非常有用。IOC容器将负责管理软件组件的创建和生命周期,并将它们注入依赖组件中,而不是手动访问这些组件实例。
例如,当某些服务需要DAO实例时,它将从容器中获取它,而不是创建它。
但在DTO的情况下,它们只保存数据,这不是真正的依赖关系。所以我认为在这种情况下使用"新"更好。