Using constructor injection

For the DI pattern with the construction injection, Spring provides you two basic options as the <constructor-arg> element and c-namespace introduced in Spring 3.0. c-namespace has less verbosity in the application, which is the only difference between them--you can choose any one. Let's inject the collaborating beans with the construction injection as follows:

    <bean id="transferService"   
class="com.packt.patterninspring.chapter4.
bankapp.service.TransferServiceImpl"> <constructor-arg ref="accountRepository"/> <constructor-arg ref="transferRepository"/> </bean>
<bean id="accountRepository"
class="com.packt.patterninspring.chapter4.
bankapp.repository.jdbc.JdbcAccountRepository"/>
<bean id="transferRepository"
class="com.packt.patterninspring.chapter4.
bankapp.repository.jdbc.JdbcTransferRepository"/>

In the preceding configuration, the <bean> element of TransferService has two <constructor-arg>. This tells it to pass a reference to the beans whose IDs are accountRepository and transferRepository to the constructor of TransferServiceImpl.

As of Spring 3.0, the c-namespace, similarly, has a more succinct way of expressing constructor args in XML. For using this namespace, we have to add its schema in the XML file, as follows:

    <?xml version="1.0" encoding="UTF-8"?> 
    <beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:c="http://www.springframework.org/schema/c" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="transferService"
class="com.packt.patterninspring.chapter4.
bankapp.service.TransferServiceImpl" c:accountRepository-ref="accountRepository" c:transferRepository-
ref="transferRepository"/>
<bean id="accountRepository"
class="com.packt.patterninspring.chapter4.
bankapp.repository.jdbc.JdbcAccountRepository"/>
<bean id="transferRepository"
class="com.packt.patterninspring.chapter4.
bankapp.repository.jdbc.JdbcTransferRepository"/> <!-- more bean definitions go here --> </beans>

Let's see how to set up these dependencies with the setter injection.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset