简体   繁体   English

使用工厂方法实例化Spring bean的原因是什么?

[英]What's the reason to instantiate Spring beans with factory methods?

I know there are constructor-based injection and setter-based injection in Spring. 我知道在Spring中有基于构造函数的注入和基于setter的注入。 When should I use factory methods to inject beans? 我应该何时使用工厂方法注入豆类?

It's rather a design matter and depends on your architecture. 这是一个设计问题,取决于您的架构。

If you have classes with static factory methods, why should you add unnecessary constructors breaking the design just to fit a DI framework? 如果您有包含静态工厂方法的类,为什么要添加不必要的构造函数来破坏设计以适应DI框架?

It's inflexible, thus Spring supports both ways. 它不灵活,因此Spring支持两种方式。


Excerpt from Joshua Bloch “Effective Java” : 摘自Joshua Bloch“Effective Java”

Item 1: Consider static factory methods instead of constructors. 第1项:考虑静态工厂方法而不是构造函数。

Static factory methods advantages: 静态工厂方法优点:

  • They have names. 他们有名字。
  • They are not required to create a new object each time they are invoked. 每次调用它们时都不需要创建新对象。
  • They can return an object of any subtype of their return type. 它们可以返回其返回类型的任何子类型的对象。
  • They reduce verbosity of creating parameterized type instances. 它们减少了创建参数化类型实例的冗长程度。

Static factory methods disadvantages: 静态工厂方法的缺点:

  • When providing only static factory methods, classes without public or protected constructors cannot be subclassed. 仅提供静态工厂方法时,不能将没有公共或受保护构造函数的类子类化。
  • They are not readily distinguishable from other static methods 它们不容易与其他静态方法区分开来

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM