怎么可以用工厂方法但没有工厂的春豆?

use*_*818 7 java spring factory javabeans

在调查代码后我发现:

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

 ...............................
Run Code Online (Sandbox Code Playgroud)

怎么可能?谢谢.

Jig*_*shi 24

来自docs

bean定义中指定的构造函数参数将用作作为参数传递给ExampleBean的构造函数.现在考虑一个变体,而不是使用构造函数,Spring被告知调用静态工厂方法来返回对象的实例:

<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"/>
Run Code Online (Sandbox Code Playgroud)
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;
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,静态工厂方法的参数是通过constructor-arg元素提供的,与实际使用的构造函数完全相同.此外,重要的是要认识到工厂方法返回的类的类型不必与包含静态工厂方法的类相同,尽管在本例中它是.实例(非静态)工厂方法将以基本相同的方式使用(除了使用factory-bean属性而不是class属性),因此这里不再讨论细节.