如何将一个spring bean的parent属性设置为另一个bean的属性?

时间:2012-04-03 21:28:04

标签: java spring

是否可以使用一个Spring bean的属性来设置另一个bean的父属性?

作为背景信息,我正在尝试将项目更改为使用容器提供的数据源,而不对Spring配置进行大的更改。

具有我想要使用的属性的简单类

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

}

spring bean配置的相关位

<!-- 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>

测试时出现异常

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

或者如果我从上面删除Spring EL,我得到这个:

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

1 个答案:

答案 0 :(得分: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>