新关键字在Spring Framework中的作用 [英] Role of new keyword in Spring Framework

查看:97
本文介绍了新关键字在Spring Framework中的作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Spring框架中,似乎 bean是创建业务逻辑中使用的对象的首选方式。

In the Spring Framework, it seems like beans are the preferred way of creating objects to use in business logic.


[依赖注入]是一个对象定义它们的依赖关系的过程,即它们使用的其他对象,只能通过构造函数参数,工厂方法的参数,或者在从工厂方法构造或返回对象实例后在对象实例上设置的属性。然后容器在创建bean时注入这些依赖项。这个过程基本上是相反的,因此名称为控制反转(IoC),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.

所以从我的简单理解来看,差异是这样的:

So from my simple understanding, the difference is something like this:

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

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

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

Is it an oversimplification to say that as a rule, in methods outside of @Configuration classes and @Bean definitions, developers should only get objects using beans? Specifically, in the case where I want a fresh object, should I inject a prototype bean instead of using the new keyword directly?

我不确定我遵循Spring约定的代码示例如下所示。

One example of code where I'm not sure I'm following Spring conventions is shown below.

// 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容器将负责管理软件组件的创建和生命周期,并将它们注入相关组件,而不是手动访问这些组件实例。

Please read this Article from beloved martin fowler. I think the IOC concepts is useful when some component in your application has a dependency to other component for some functionality to complete. IoC container will be responsible for managing creation and lifecycle of software components and also inject them in dependent components instead of manually get access to these components instances.

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

For example, when some Service require an instance of DAO, it will get it from container instead of creating it.

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

But in case of DTO, they will just hold the data and that is not a real dependency. So I think using "new" is better in this case.

这篇关于新关键字在Spring Framework中的作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆