春天-使用新方法不好吗? [英] Spring - is using new a bad practice?
问题描述
是否手动创建对象 ,即使用new
运算符而不是注册Spring
bean并使用依赖项注入被认为是不好的做法?我的意思是,Spring IoC
容器是否必须了解应用程序中的所有对象?如果是这样,为什么?
Is creating objects by hand, i.e. using new
operator instead of registering Spring
bean and using dependency injection considered bad practice? I mean, does Spring IoC
container have to know about all objects in the application? If so, why?
推荐答案
您希望Spring为以下类创建bean :
- 您想要/需要在其他bean中注入实例
- 您需要在自己的实例中注入bean(或依赖项).
- 您希望他们受益于Spring功能(实例化管理,事务管理,Spring授权的代理类,例如Repository/Interceptor等)
服务,控制器或拦截器就是它们的示例.
例如,控制器可能需要注入服务或拦截器.
同样,您也不想通过为每个类实现单例模式来处理这些类的实例化.这可能容易出错,并且需要样板代码.
因此,您希望所有这些类都是由Spring管理的bean.
Services, controllers or interceptors are example of them.
For example a controller may need inject a service or an interceptor.
As well as you don't want to handle the instantiation of these classes by implementing yourself the singleton pattern for each one. Which could be error-prone and require boiler plate code.
So you want all of these classes to be beans managed by Spring.
但是您不想Spring为以下类创建bean :
- 您不想/不需要在其他bean中注入实例
- 您不需要在自己的实例中注入bean(或依赖关系)
- 您不需要他们从Spring功能中受益
实体,DTO,价值对象就是它们的示例.
Entity, DTO, Value Object are example of them.
例如,一个实体永远不需要作为依赖项注入到另一个实体或服务中,因为这些实体不是在容器启动时创建的,而是通常在方法内部创建的,并且范围限于方法的寿命. >
同样,您也不需要Spring创建使用生命周期作为方法的实例. new
运算符做得很好.
因此,将它们定义为bean实例是没有意义的,甚至显得非常直观.
For example an entity never needs to be injected into another entity or in a service as a dependency because entities are not created at the container startup but are generally created inside a method and have a scope limited to the methods lifespan.
As well as you don't need Spring to create instances which the lifespan is a method. The new
operator does very well the job.
So defining them as bean instances makes no sense and appears even counter intuitive.
这篇关于春天-使用新方法不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!