0

是否可以使用一个 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
4

1 回答 1

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>
于 2012-04-03T21:49:36.417 回答