Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can be spring bean with factory-method but without factory? [closed]

After investigation of code I found:

 <bean id="TestBean" class="com.test.checkDate"
 factory-method="getPreviousDate">
 <constructor-arg value .............

 ...............................

How it can be possible? Thanks.

like image 683
user710818 Avatar asked Oct 31 '11 10:10

user710818


1 Answers

From docs

the constructor arguments specified in the bean definition will be used to pass in as arguments to the constructor of the ExampleBean. Now consider a variant of this where instead of using a constructor, Spring is told to call a static factory method to return an instance of the object:

<bean id="exampleBean" class="examples.ExampleBean"
      factory-method="createInstance">
  <constructor-arg ref="anotherExampleBean"/>
  <constructor-arg ref="yetAnotherBean"/>
  <constructor-arg value="1"/> 
</bean>

<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>

public class ExampleBean {

    // a private constructor
    private ExampleBean(...) {
      ...
    }

    // a static factory method; the arguments to this method can be
    // considered the dependencies of the bean that is returned,
    // regardless of how those arguments are actually used.
    public static ExampleBean createInstance (
            AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {

        ExampleBean eb = new ExampleBean (...);
        // some other operations...
            return eb;
    }
}

Note that arguments to the static factory method are supplied via constructor-arg elements, exactly the same as if a constructor had actually been used. Also, it is important to realize that the type of the class being returned by the factory method does not have to be of the same type as the class which contains the static factory method, although in this example it is. An instance (non-static) factory method would be used in an essentially identical fashion (aside from the use of the factory-bean attribute instead of the class attribute), so details will not be discussed here.

like image 69
jmj Avatar answered Nov 05 '22 19:11

jmj