Sunday, June 16, 2013

Spring Constructor Autowiring

            Constructor autowiring is similar to “byType” for constructor argument. If you define attribute autowire=”constructor” in bean configuration spring container will wire the bean into constructor which is same type of constructor argument.
            If there is no exactly one bean of the constructor argument type in the bean configuration file spring container will throws no unique bean exception.
            If there is multiple beans of the constructor argument type in the bean configuration file but your constructor argument name is matching with any one of the bean id in the configuration file no issues. In this case byName and byType wiring will be applicable on your bean.
            Here is my bean configuration file.


applicationContext.xml

            Here my CustomerServiceImpl bean configuration I have added attribute autowire=”constructor”. So there should be a constructor defined in CustomerServiceImpl.java class with argument type is CustomerDaoImpl.

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

       <bean id="customerDaoImpl" class="com.lova.springautwire.dao.CustomerDaoImpl" />
      
       <bean id="customerServiceImpl" class="com.lova.springautowire.service.CustomerServiceImpl" autowire="constructor"/>
</beans>

CustomerDoImpl.java

            Same as my previous example.

package com.lova.springautwire.dao;

/**
 * @author Lovababu
 *
 */
public class CustomerDaoImpl {

       public void daoMethod() {
              System.out.println(".Dao.daoMethod()");
       }
}

CustomerServiceImpl.java

            Here I have defined constructor in such way that can accept CustomerDaoImpl object as an argument. Here argument need not be same as bean id of other bean in configuration file if and only if there is exactly one bean of constructor argument type in configuration file.

package com.lova.springautowire.service;

import com.lova.springautwire.dao.CustomerDaoImpl;

/**
 * @author Lovababu
 *
 */
public class CustomerServiceImpl
{
       private CustomerDaoImpl daoImpl;
       //arguement name need not be the same as bean id in bean config file.
      
       public CustomerServiceImpl(CustomerDaoImpl customerDaoImpl){
              this.daoImpl = customerDaoImpl;
       }

       public void serviceMethod()
       {
              System.out.println(".Service.serviceMethod().START");
              daoImpl.daoMethod();
              System.out.println(".Service.serviceMethod().END");
       }

}

AutowireConstructorTest.java

            Same as AutowirebyName example.

No comments:

Post a Comment

UA-41474183-1