![](/img/trans.png)
[英]spring: set property of one bean by reading the property of another bean?
[英]How to set the parent attribute of one spring bean to a property of another bean?
是否可以使用一個 Spring bean 的屬性來設置另一個 bean 的父屬性?
作為背景信息,我正在嘗試更改項目以使用容器提供的數據源,而無需對 Spring 配置進行大量更改。
帶有我想使用的屬性的簡單 class
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 beans 配置的相關位
<!-- 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.