Java Reference
In-Depth Information
access the resources that it needs, such as a
JDBC
DataSource
. The trouble with
JNDI
is that it couples application code to the application server, which makes
development and testing more difficult. The Spring framework provides
POJO
s
with a much easier-to-use mechanism called
dependency injection
, which decouples
application components from one another and from the application server.
Dependency injection is another powerful feature of Spring's bean factory.
Spring beans can be configured to depend on other beans, and when Spring
instantiates a bean, it will pass to it any required beans, instantiating them if nec-
essary. Two main types of dependency injection are used with Spring: constructor
injection and setter injection. With constructor injection, the container passes the
required objects to a component's constructor; with setter injection, the con-
tainer passes the required objects by calling setters.
Dependency injection was used earlier to wire together the Spring beans—
TransactionInterceptor
,
PlatformTransactionManager
, and
BeanNameAutoProxy-
Creator
—that provide transaction management. It can also be used to wire
together application components. In the money transfer example, we can config-
ure the
TransferFacade
bean to depend on
TransferService
and
Transfer-
Service
to depend on
HibernateAccountRepository
and
HibernateBanking-
TransactionRepository
:
<beans>
…
<bean id="TransferFacade"
class="TransferFacadeImpl">
<constructor-arg ref="TransferService"/>
</bean>
<bean id="TransferService"
class=" TransferServiceImpl">
<constructor-arg ref="AccountRepository"/>
<constructor-arg ref="BankingTransactionRepository"/>
</bean>
…
</beans>
The first bean definition specifies that
TransferFacadeImpl
's constructor take a
TransferService
as a parameter. The second bean definition specifies that
Trans-
ferServiceImpl
's constructor be passed
AccountRepository
and
BankingTrans-
actionRepository
. When Spring instantiates
TransferFacade
, it will also instantiate
TransferService
,
HibernateAccountRepository
, and
HibernateBankingTrans-
actionRepository
. See the online source code, which can be downloaded from
Search WWH ::
Custom Search