2012-04-03 90 views
0

是否可以使用一個Spring bean的屬性來設置另一個bean的父屬性?如何將一個spring bean的父屬性設置爲另一個bean的屬性?

作爲背景信息,我試圖將項目更改爲使用容器提供的數據源,而不對Spring配置進行大的更改。

與我想要使用Spring配置豆

<!-- new --> 
<bean id="springPreloads" class="sample.SpringPreloads" /> 

<!-- How do I set the parent attribute to a property of the above bean? --> 
<bean id="abstractDataSource" class="oracle.jdbc.pool.OracleDataSource" 
abstract="true" destroy-method="close" parent="#{springPreloads.dataSource}"> 
    <property name="connectionCachingEnabled" value="true"/> 
    <property name="connectionCacheProperties"> 
     <props> 
      <prop key="MinLimit">${ds.maxpoolsize}</prop> 
      <prop key="MaxLimit">${ds.minpoolsize}</prop> 
      <prop key="InactivityTimeout">5</prop> 
      <prop key="ConnectionWaitTimeout">3</prop> 
     </props> 
    </property> 
</bean> 

異常的

package sample; 

import javax.sql.DataSource; 

public class SpringPreloads { 

    public static DataSource dataSource; 

    public DataSource getDataSource() { 
     return dataSource; 
    } 

    //This is being set before the Spring application context is created 
    public void setDataSource(DataSource dataSource) { 
     SpringPreloads.dataSource = dataSource; 
    } 

} 

相關位進行測試時,一個簡單的財產類

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '#{springPreloads.dataSource}' is defined 

,或者如果我從上面拆下彈簧EL我得到這個:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'springPreloads.dataSource' is defined 
+0

我不確定你要在這裏做什麼。父級是模板配置,這是與abstractDataSource bean不同的類。將屬性從一個bean注入到另一箇中有一個很好的「訣竅」,但這似乎並不是你想要的。 – Adam 2012-04-03 21:40:45

回答

1

我覺得這是你追求的。 SpringPreloads bean被用作「工廠」,但只是爲了獲得其dataSource屬性,然後插入各種屬性...

我猜springPreloads.dataSource是oracle.jdbc的一個實例。 pool.OracleDataSource?

<bean id="springPreloads" class="sample.SpringPreloads" /> 

<bean id="abstractDataSource" factory-bean="springPreloads" factory-method="getDataSource"> 
    <property name="connectionCachingEnabled" value="true" /> 
    <property name="connectionCacheProperties"> 
     <props> 
      <prop key="MinLimit">${ds.maxpoolsize}</prop> 
      <prop key="MaxLimit">${ds.minpoolsize}</prop> 
      <prop key="InactivityTimeout">5</prop> 
      <prop key="ConnectionWaitTimeout">3</prop> 
     </props> 
    </property> 
</bean> 
相關問題