What is the difference between spring factory-method and factory-bean?

前端 未结 6 2032
小鲜肉
小鲜肉 2021-02-02 10:28

I am new Springs. In Bean tag I found factory-method and factory-bean Attributes. What is the difference between factory-method and factory-bean?

I am using factory-meth

6条回答
  •  悲&欢浪女
    2021-02-02 10:38

    It's basically the same difference between the Factory method and Factory design patterns, with a little note at the bottom. While one is a method used to obtain instances of a specific class, the other is a full fledged object responsible of creating objects, including all of the required logic to do so.

    FactoryBean's interface documentation states:

    Interface to be implemented by objects used within a BeanFactory which are themselves factories. If a bean implements this interface, it is used as a factory for an object to expose, not directly as a bean instance that will be exposed itself.

    Also, this object is not used as a bean instance, but as an instance provider through its getObject method.


    Update

    Searching for uses of factory-method over a FactoryBean, it seems that it used quite oftenly with legacy singleton beans, to get the underlying instance, but this approach doesn't provide support for initialization methods, such as, for example, an init method that initializes a given set of properties.

    In this case, you either have to invoke it yourself before using the class, define a wrapper that handles the initialization or make use of other mechanisms such as MethodInvokingFactoryBean.


    Update 2

    Strictly speaking, a FactoryBean is intended to manage a specific type. You'd have, in fact, an EggPlantFactory, not a VegetableFactory since the getObject method defined by the FactoryBean interface doesn't support parameters.

提交回复
热议问题