Autowiring in Spring

Autowiring in Spring

Autowiring feature of spring framework enables you to inject the object dependency implicitly. It internally uses setter or constructor injection.
Autowiring can't be used to inject primitive and string values. It works with reference only.

Advantage of Autowiring

It requires the less code because we don't need to write the code to inject the dependency explicitly.

Disadvantage of Autowiring

No control of programmer.
It can't be used for primitive and string values.

Autowiring Modes

There are many autowiring modes:
No.
Mode
Description
1)
no
It is the default autowiring mode. It means no autowiring bydefault.
2)
byName
The byName mode injects the object dependency according to name of the bean. In such case, property name and bean name must be same. It internally calls setter method.
3)
byType
The byType mode injects the object dependency according to type. So property name and bean name can be different. It internally calls setter method.
4)
constructor
The constructor mode injects the dependency by calling the constructor of the class. It calls the constructor having large number of parameters.
5)
autodetect
It is deprecated since Spring 3.

Practically bean dependencies are explicitly set in bean configuration files and it is really is a good practice to follow. But Spring is capable of automatically resolving dependencies at runtime. This automatic resolution of bean dependencies is also called autowriring. This type of bean dependencies can also be referred to as collaborating beans or just as collaborators.
There are 5 different types of autowiring modes which are ‘no’, ‘byName‘, ‘byType‘, ‘constructor’, and ‘autodetect‘.
no: This option is default for spring framework and it means that autowiring is OFF. You have to explicitly set the dependencies using <property> tags in bean definitions.
Autowiring by Name
This option enables the dependency injection based on bean names. When autowiring a property in bean, property name is used for searching a matching bean definition in configuration file. If such bean is found, it is injected in property. If no such bean is found, a error is raised.
Autowiring by name allows a property to be autowired such that it will inspect the container and look for a bean named exactly the same as the property which needs to be autowired. For example, if you have a bean definition which is set to autowire by name, and it contains a “dept” property (i.e. it has a setDept(..) method), container will look for a bean definition named departmentBean, and if found, use it to set the property.
Autowire By Constructor
Autowiring by constructor is similar to byType, but applies to constructor arguments. In autowire enabled bean, it will look for class type of constructor arguments, and then do a autowire by type on all constructor arguments.
If you are not using autowire="constructor" in bean definition, then pass the constructor-arg.
Autowiring by Type
Autowiring by type allows a property to be autowired if there is exactly one bean of the property type in the container. If there is more than one, a fatal exception is thrown, and this indicates that you may not use byType autowiring for that bean.

Autowiring by autodetect

Autowiring by autodetect uses either of two modes i.e. constructor or byType modes. First it will try to look for valid constructor with arguments, If found the constructor mode is chosen. If there is no constructor defined in bean, or explicit default no-args constructor is present, the autowire byType mode is chosen.


All Autowire Example


Department.java

package com.smgc;

public class Department {
       private String name;

       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }
}

Employee.java

package com.smgc;

public class Employee {
       private String fullName;
       private Department dept;

       public Employee()
    {
       
    }
      
       public Employee(Department dept)
    {
        this.dept = dept;
    }
      
       public String getFullName() {
              return fullName;
       }

       public void setFullName(String fullName) {
              this.fullName = fullName;
       }

       public Department getDept() {
              return dept;
       }

       public void setDept(Department dept) {
              this.dept = dept;
       }
}

TestAutoWire.java

package com.smgc;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAutowire {

                public static void main(String[] args) {
                                // TODO Auto-generated method stub
                                ApplicationContext context = new ClassPathXmlApplicationContext(
                                                                new String[] { "myBean.xml" });

/*                           System.out.println("Autowire By Name");
        System.out.println("-----------------------");
                                Employee employee = (Employee) context.getBean("emp1");
                                System.out.println(employee.getFullName());
                                System.out.println(employee.getDept().getName());
                */          
                                System.out.println("Autowire By Type");
        System.out.println("-----------------------");
        Employee employee = (Employee) context.getBean("emp4");
                                System.out.println(employee.getFullName());
                                System.out.println(employee.getDept().getName());

/*                           System.out.println("Autowire By Constructor");
                                System.out.println("-----------------------");
                                employee = (Employee) context.getBean("emp2");
                                System.out.println(employee.getFullName());
                                System.out.println(employee.getDept().getName());

                                System.out.println("Autowire By Constructor");
                                System.out.println("-----------------------");
                                employee = (Employee) context.getBean("emp3");
                                System.out.println(employee.getFullName());
                                System.out.println(employee.getDept().getName());
*/          
                               
                }
}


myBean.xml

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

       <bean id="emp1" class="com.smgc.Employee" autowire="byName">
              <property name="fullName" value="Piyush Patel" />
       </bean>

       <bean id="department" class="com.smgc.Department">
              <property name="name" value="Computer Department" />
       </bean>

       <bean id="emp2" class="com.smgc.Employee" autowire="constructor">
              <property name="fullName" value="Monali Bhanushali" />
       </bean>

       <bean id="emp3" class="com.smgc.Employee">
              <property name="fullName" value="Aarti Kubavat" />
              <constructor-arg>
                     <ref bean="department" />
              </constructor-arg>
       </bean>
      
       <bean id="emp4" class="com.smgc.Employee" autowire="byType">
        <property name="fullName" value="Piyush Patel"/>
    </bean>

</beans>



 Output:

Run1:

Autowire By Type
-----------------------
Piyush Patel
Computer Department


Run2:

Autowire By Name
-----------------------
Piyush Patel
Exception in thread "main" java.lang.NullPointerException
at com.smgc.TestAutowire.main(TestAutowire.java:17)


Run3:

Autowire By Constructor
-----------------------
Monali Bhanushali
Computer Department
Autowire By Constructor
-----------------------
Aarti Kubavat
Computer Department


Comments

Popular posts from this blog

પટેલ સમાજનો ઈતિહાસ જાણો : કોણ અને ક્યાંથી આવ્યા હતા પાટીદારો

Python HTML Generator using Yattag Part 1

Java Event Delegation Model, Listener and Adapter Classes