【问题标题】:How to set the parent attribute of one spring bean to a property of another bean?如何将一个spring bean的父属性设置为另一个bean的属性?
【发布时间】:2012-04-03 21:28:04
【问题描述】:

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

作为背景信息,我正在尝试更改项目以使用容器提供的数据源,而不对 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

【问题讨论】:

  • 我不确定您要在这里做什么。父级是模板配置,它与 abstractDataSource bean 不同。将属性从一个 bean 注入到另一个 bean 有一个很好的“技巧”,但这似乎不是您所追求的。

标签: java spring


【解决方案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>

【讨论】:

    猜你喜欢
    • 2010-12-08
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 2017-01-03
    • 1970-01-01
    • 2012-11-13
    相关资源
    最近更新 更多