Spring自动装配的Bean与手动创建的实例之间的区别

huangapple go评论65阅读模式
英文:

Spring autowired beans vs created instances

问题

当我看到典型的Spring Web应用程序时,所有实例都由Spring创建和注入,我们通过传递一些参数来使用方法。其中大多数实例都是单例的,不保存任何状态。

我可能错了,但这种方法对我来说更像是过程导向而不是面向对象的。我认为良好的设计应该同时利用由Spring管理的Bean和由用户创建的带有一些状态和方法以公开某些行为的实例。

在特定上下文中,是否应该使用注入的单例Bean还是手动创建的实例,是否有一个经验法则?如果我们过度使用每个接收的请求的短寿命实例,是否会有性能影响?我想了解在这种情况下设计我的类的适当方式。

英文:

When I see typical spring web application, all the instances are created and injected by spring, and we use methods by passing some arguments. Majority of these instances are singleton and don't hold any state with it.

I may be wrong, but this approach looks more procedure oriented than object oriented for me. I assume good design should utilize both spring manged beans along with instances created by user which hold some state and with methods to expose some behaviour.

Is there a rule of thumb to decide which one we should use(injected singleton beans or manually created instance) in a context? Also is there a performance impact if we excessively used short lived instances per request received? Would like to know proper way to design my classes in this scenario.

答案1

得分: 1

Singleton是Spring的默认范围,用于在应用程序中不需要具有相同状态时使用。但是,如果出于任何原因需要基于Spring的bean创建实例,可以更改范围并创建一个基于Prototype而不是Singleton的bean。

当然,您不需要将bean用于DAO对象,只需在需要的地方传递它,就像您在其他网站上看到的那样。

另一方面,如果基于Prototype模式创建大量对象,性能显然会受到影响,因为每次都会创建新对象(幸运的是,垃圾收集器会清理它,所以现在不应该太担心)。

有关更多信息,请参阅:https://docs.spring.io/spring-framework/docs/3.0.0.M4/reference/html/ch03s05.html#beans-factory-scopes-prototype

英文:

Depends of your need, Singleton its used by default for Spring and its used when you don't need have the same state in the application, but if for any reason you need a instance based on the beans of spring you can change the scope and create a bean based on Prototype instead of Singleton

And of course you don't need use the bean for DAO objects, just pass it where is needed as you saw in other sites

By other way, the performance obviously can be affected if you create a lot of objects based on Prototype pattern, because you create new object every time (For our luck the garbage collector cleans that so, you don't should be too afraid by now)

And for more information about that: https://docs.spring.io/spring-framework/docs/3.0.0.M4/reference/html/ch03s05.html#beans-factory-scopes-prototype

huangapple
  • 本文由 发表于 2023年4月17日 21:54:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76035928.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定