2012-07-11 35 views
0

我有兩個疑問引用豆新的bean實例...讓每一次

1)我有豆Spring容器本身的intialized當Spring容器intialiazed並在撥打電話前查詢到get bean()方法,這是默認行爲,我怎樣才能以這樣的方式配置應用程序,使得只有在調用getbean()時才允許bean在容器中初始化,我們是否應該將bean聲明爲原型爲了達成這個。

2)第二個查詢是第一請到通過下面的例子中第一...

<beans> 
<bean id="triangle" class="Demo.Triangle" scope="singleton" > 
<property name="pointA" ref="zeropoint"/> 
<property name="pointB" ref="firstpoint"/> 
<property name="pointC" ref="secondpoint"/> 
</bean> 

<bean id="zeropoint" class="Demo.Point" scope="prototype" > 
<property name="x" value="10" /> 
<property name="y" value="20" /> 
</bean> 


<bean id="firstpoint" class="Demo.Point" scope="prototype" > 
<property name="x" value="10" /> 
<property name="y" value="20" /> 
</bean> 

<bean id="secondpoint" class="Demo.Point" scope="prototype"> 
<property name="x" value="10" /> 
<property name="y" value="20" /> 
</bean> 

正如上面那個三角形豆表明是單以及它引用的bean是protoype現在,當我訪問獨居其他refernces bean的zeropoint,firstpoint和secondpoint也只是針對三角形初始化一次,但是在這裏我希望每當這個三角形bean被提取時創建這三個bean的新實例,請告知這是如何實現的。它是通過我的POJO實現了ApplicationContextAware接口實現的,請大家指教

回答

2
  1. 其所謂Lazy loading

    <bean id="myBean" class="a.b.MyBean" lazy-init="true"/>

    • 首先請注意,您firstpointsecondpoint bean沒有一個有效的範圍定義(您錯過了scope=
    • 原型範圍mea每個需要原型bean的bean都有自己的實例。如果要定義多個三角形,它們都對zeropoint有依賴關係,那麼每個三角形就會有一個單獨的zeropoint實例。
    • 如果您需要三角形類中的新點實例(例如,每一次調用三角形的方法),最好的辦法就是直接從bean工廠收到的實例:

例如

class MyClass implements BeanFactoryAware { 

    private BeanFactory beanFactory; 

    public void setBeanFactory(BeanFactory beanFactory) { 
    this.beanFactory = beanFactory; 
    } 

    public void doSomethingThatRequiresNewInstance() { 
    Triangle t = beanFactory.getBean("zeropoint", Triangle.class); 
    // because zeropoint is defined as prototype you get a new instance everytime you call getBean(..) 
    } 
} 
+0

thanka很多,完美的探索,保持它.. – user1508454 2012-07-11 18:17:17

3

而不是依賴於Spring基礎設施(BeanFactoryAware)我建議嘗試查找方法特點:

abstract class Triangle { 

    public abstract Point createZeroPoint(); 
    public abstract Point createFirstPoint(); 
    public abstract Point createSecondPoint(); 

    public void foo() { 
     Point p0 = createZeroPoint(); 
     Point p1 = createFirstPoint(); 
     Point p2 = createSecondPoint(); 
    } 

} 

每次調用create*Point()抽象方法時,它創建的Point新實例。但是,你如何實現這個方法,以及它如何知道返回哪個bean? Spring爲你實現這個!

<bean id="triangle" class="Demo.Triangle" scope="singleton"> 
    <lookup-method name="createZeroPoint" bean="zeropoint"/> 
    <lookup-method name="createFirstPoint" bean="firstpoint"/> 
    <lookup-method name="createSecondPoint" bean="secondpoint"/> 
</bean> 

查看全面的文檔:4.4.6.1 Lookup method injection

+0

感謝這個信息..我不知道這個功能:o – micha 2012-07-14 17:26:34

相關問題