2011-10-31 62 views
7

的代碼調查後,我發現:工廠方法但沒有工廠的春豆怎麼可能?

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

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

它如何可能呢? 謝謝。

+0

「無工廠」的含義是什麼?如果你可以重新解釋這個問題,它可能有助於得到答案。 –

回答

24

從文檔

在bean定義中指定的構造器參數將被 用於傳遞作爲參數傳遞給叫exampleBean的構造函數。 現在考慮的這個變體,其中,代替使用構造, 春天被告知調用靜態工廠方法返回一個實例對象的 :

<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; 
    } 
} 

請注意,靜態工廠方法的參數通過 constructor-arg元素提供,與實際使用的構造函數實際上具有 完全相同。此外,重要的是要認識到,工廠方法返回的類別 的類型不必是 與包含靜態工廠方法的類相同的類型,儘管在本示例中是 。實例(非靜態)工廠 方法將以基本相同的方式使用(除了使用factory-bean屬性而不是 而不是類屬性), ,因此在此不討論細節。

+1

謝謝...你爲我節省了一些寶貴的時間。 – Lahniep

1

它只是意味着com.test.checkDate有一個名爲getPreviousDate的靜態方法。您的工廠創建對象是com.test.checkDate。我們不知道哪個類型是返回的對象,不是在配置中說的,可能是java.util.Date

該定義沒有指定返回對象的類型(類),只包含了包含工廠方法的類。

constructor-arg僅作爲參數傳遞給getPreviousDate。由於該方法是靜態的,因此不需要checkDate的實例。如果使用constructor-arg調用技術上不是構造函數的方法聽起來很有趣,那麼認爲靜態方法的確在構造一個Object,因此它會更容易記住。

因爲在你的答案的早期版本中,你提到的「無工廠」,也許你正在考慮的instantiation using an instance factory method的情況下,這就要求factory-bean屬性,但是這是Instantiation with a static factory method的情況。