How can there be a spring bean with a factory method, but without a factory?

After studying the code, I found:

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

How is this possible? Thanks.

+7
source share
2 answers

From the documents

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

 <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 the arguments to the static factory method are provided through the-arg constructor, just as if the constructor were actually used. In addition, it is important to understand that the type of the class returned by the factory method does not have to be the same type as the class containing the static factory method, although this is the case in this example. An instance of a (non-static) factory method will be used essentially the same (except for using the factory-bean attribute instead of the class attribute), so the details will not be discussed here.

+24
source

It just means that com.test.checkDate has a static method called getPreviousDate . Creating factory objects com.test.checkDate . We do not know what type the returned object is, is not specified in the configuration, perhaps it is java.util.Date .

the type (class) of the returned object is not specified in the definition, but only the class containing the factory method.

constructor-arg simply passed as parameters to getPreviousDate . Since the method is static, it does not need an instance of checkDate . If itโ€™s ridiculous to use constructor-arg to call a method that is technically not a constructor, think that the static method actually creates the object, so it will be easier to remember.

Since you mentioned โ€œno factoryโ€ in an earlier version of your answer, you are probably thinking of creating an instance using an instance of a factory method that requires a factory-bean attribute, but this applies to Activation with a static factory method .

+1
source

All Articles