gpt4 book ai didi

java - Spring Framework中new关键字的作用

转载 作者:搜寻专家 更新时间:2023-11-01 03:34:09 24 4
gpt4 key购买 nike

在 Spring Framework 中,它看起来像 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 获取对象,这样说是否过于简单化?具体来说,在我想要一个新对象的情况下,我应该注入(inject)一个原型(prototype) 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 容器将负责管理软件组件的创建和生命周期,并将它们注入(inject)依赖组件,而不是手动访问这些组件实例。

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

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

关于java - Spring Framework中new关键字的作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36776547/

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