是否可以使用一个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;
}
}
弹簧豆配置的相关部分
<!-- 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
我想这就是你想要的。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>