java – Spring关键字在Spring Framework中的作用


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获取对象?具体来说,在我想要一个新鲜对象的情况下,我应该注入原型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”更好.

点赞