Search
Calendar
June 2025
S M T W T F S
« May    
1234567
891011121314
15161718192021
22232425262728
2930  
Archives

PostHeaderIcon Get a field of a bean in Spring

Case

I have to instanciate an object of type FooDao. The only constructor available is FooDao(Connection connection).

On another hand, I have a bean of type BasicDataSource. From this BasicDataSource, I can get a Connection, through the call of BasicDataSource.getConnection().

Question: how to instanciate a bean of type FooDao in Spring?

Solution

The idea, to retrieve a field member of a bean, is to use the attributes factory-bean and factory-method, from which we will get a new bean.

Use the following Spring context file:


<bean id="myBasicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!-- complete ... -->
</bean>

<bean id="connection" factory-bean="myBasicDataSource" factory-method="getConnection"
scope="singleton"/>

<bean id="myFooDao" class="com.my.company.FooDao">
     <constructor-arg ref="connection"/>
</bean>

Many thanks to David Chau from SFEIR for his help in this issue!

Leave a Reply