Datasheet
2. Uses it to look up a resource bound at jdbc/WroxJDBCDS
3. Casts the returned resource to a DataSource
When writing your software components to be wired by Spring, however, you do not need to perform the
lookup; you just start to use the DataSource. Consider this segment of code from a Spring component:
private DataSource ds;
public void setDs(DataSource datasource) {
ds = datasource;
}
...
Connection conn = ds.getConnection(“user”, “pass”);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( “SELECT * FROM Cust” );
while( rs.next() )
System.out.println( rs.getString(1)) ;
rs.close() ;
stmt.close() ;
conn.close() ;
This code does exactly the same work as the preceding code segment. However, note that at no time does
the component actually ask the container for the DataSource. Instead, the code simply uses the private
ds
variable without knowing how it is obtained.
In this case, control over deciding which DataSource to use is not with the component — it is with the
container. Once the container has an instance of a DataSource that the component can use, it is placed
into the object by calling the
setDs() method. This is the inversion in IoC! The control for the resource
to use is inverted, from the component to the container and its configuration. In this case, the Spring
container makes the decision instead of the component.
Of course, in Spring, the DataSource can be wired during deployment via editing of the
beans.xml
descriptor file:
<bean name=”wroxBean”
class=”com.wrox.beginspring.DataBean”>
<property name=”ds” ref=”jdbcds” />
</bean>
The preceding code assumes that the jdbcds bean is a DataSource that has been wired earlier within the
context descriptor. This DataSource instance can be created directly as a
<bean>, or it can still use JNDI
lookup if the container chooses. Spring provides a library factory bean called
org.springframework
.jndi.support.SimpleJndiBeanFactory
, if you want to use JNDI lookup.
The key thing to understand is that instead of you having to decide on the mechanism to obtain a resource
(such as a JDBC DataSource) in the component code — making it specific to the means of lookup and hard-
coding the resource name — using IoC allows the component to be coded without any worry about this
detail. The decision is deferred to the container to be made at deployment time instead of at compile time.
Figure 1-3 illustrates IoC.
The component on the left side of Figure 1-3 is a standard non-IoC component, and it asks the container
for the two resources (beans) that it needs. On the right side of Figure 1-3, the container creates or locates
17
Chapter 1: Jump Start Spring 2
01612c01.qxd:WroxPro 10/31/07 10:42 AM Page 17