2012-04-03 91 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> 
相关问题