@Autowired can also be used with Setter method though Spring Container detects the bean instance using byType process only and inject the bean property using Setter Injection. Using @Autowired with the Setter means wiring at the property head. There will not be any need to configure XML with the <constructor-arg> tag. It is same as byType autowiring prcoess with a difference of mapping style. 

Example showing the Annotation on Setter :
There are two bean class A and Hello and Hello is having dependency of A.

A.java
public class A {  } 

Hello.java
public class Hello {
  
 A a;                                 // Bean Property
public Hello(){ //Default Constructor System.out.println("Hello instance "); } public Hello(A a){ System.out.println("Arg Cons"); //Constructor Injection this.a = a; } @Autowired //Annotation on properties public void setA(A a) {  System.out.println("Setter Injection"); //Setter Injection this.a = a; }
   public static void main(String[] args) {
  
       ApplicationContext ctx= new ClassPathXmlApplicationContext("SpringCore.xml");
       Hello hello =(Hello)ctx.getBean("hello");
 }

}

SpringCore.xml
<bean id="a" class="com.def.A"> 
</bean>

<bean id="hello" class="com.def.Hello" >
</bean>

Output
Def A cons
Hello Instance
Setter Injection

In the above example
1. Instance of bean A will be created by calling default constructor.
2. Instance of bean Hello will be created by calling default constructor.
3. Bean property will be injected using Setter Injection.

Note : In the above example has output of argumented constructor hence uses Constructor Injection for injecting bean property.

Note: In the above example it is using @Autowired with the Setter that means Setter Injection, so the instance of the Hello is created first and then inject the Bean property.

@Autowired can also be used with Constructor by which Spring Container detects the bean instance using byType process but inject the bean property using Constructor Injection. Using @Autowired with the Constructor, there is not need to configuring XML with the <constructor-arg> tag. It is same as constructor autowiring prcoess with a difference of mapping style. 

Example showing the Annotation on Constructor :
There are two bean class A and Hello and Hello is having dependency of A.

A.java
public class A {  } 

Hello.java
public class Hello {
  
 A a;                             // Bean Property
public Hello(){ //Default Constructor System.out.println("Hello instance "); } @Autowired //Annotation on properties public Hello(A a){ System.out.println("Arg Cons");//Constructor Injection this.a = a; } public void setA(A a) { //Setter Injection this.a = a; } public static void main(String[] args) { ApplicationContext ctx= new ClassPathXmlApplicationContext("SpringCore.xml"); Hello hello =(Hello)ctx.getBean("hello"); } }

SpringCore.xml
<bean id="a" class="com.def.A"> 
</bean>

<bean id="hello" class="com.def.Hello" >
</bean>

Output
Def A cons
Arg Cons

In the above example ,
1. Instance of bean A will be created by calling default constructor.
2. Instance of bean Hello will be created by calling argumenetd constructor.
3. Bean property will be injected using Constructor Injection.

Note : In the above example has output of argumented constructor hence uses Constructor Injection for injecting bean property.

@Autowired is used on Properties, which means Spring Container detects the bean instance using the byType process but injection is not with Setter method.This is how byType auto-wiring process is different from Annotation based auto-wiring. Hence annotation tells no need to write any setter method or constructor for injecting the bean property.

Example showing the Annotation on Properties :
There are two bean class A and Hello and Hello is having dependency of A.

A.java
public class A {  } 

Hello.java
public class Hello {
  
 @Autowired           //Annotation on properties
 A a;
public Hello(){ //Default Constructor System.out.println("Hello instance "); } public Hello(A a){ //Constructor Injection System.out.println("Arg Cons"); this.a = a; } public void setA(A a) { //Setter Injection this.a = a; } public static void main(String[] args) { ApplicationContext ctx= new ClassPathXmlApplicationContext("SpringCore.xml"); Hello hello =(Hello)ctx.getBean("hello"); } }

SpringCore.xml
<bean id="a" class="com.def.A"> 
</bean>

<bean id="hello" class="com.def.Hello" >
</bean>

Output
Def A cons
Hello instance

In the above example
1. Instance of bean A will be created using default constructor.
2. Instance of bean Hello will be created using default constructor.
3. Bean property will be injected but without setter and constructor injection.

Note : In the above example output doesn't involve any constructor or setter injection hence proved that it follows different approach for injecting the bean property rather using Constructor or Setter Injection.

Note : Annotation on properties rather follows different approach to inject the bean property.


Auto-wiring in spring can also be achieved through Annotation. Annotation is the simplest way to achieve wiring in Spring as it doesn't involve any extra code in XML file. It can be parsed by the Spring container at the time of reading the bean class. An the strange fact is that annotation auto-wiring doesn't use any of the constructor or setter injection for injection the bean property else it uses its own way to inject the bean property. But bean will be detected using the byType process. Annotation can be used with the bean properties, setter method and constructor.

@Autowired is the annotation can be used with the bean properties, constructor and Setter method.

1. Annotation on properties
2. Annotation on constructor
3. Annotation on Setter
4. Annotation on properties where ( required = false )

Note : By default annotation in Spring is disabled, we have to enable it manually by modifying the XML file.

For Enabling Annotation in Spring 

Why Annotation is by default disable in Spring ?
It is because in Spring all the functionality is not supported by annotation rather it is possible with using XML file.

Cyclic dependency is the one of the major limitation of the Injection process in Spring. Constructor Injection has chance of having Cyclic Dependency, while the same is not possible in case of Setter Injection.

When both the beans depends on each other for injecting the bean property then it forms the Cyclic Dependency. In Cyclic Dependency containers goes on infinite loop for getting the bean instance, so to avoid this type of situation ( Cyclic Chaining ) it finally create the instance of second bean by calling default constructor. So as a result only one bean will be injected and another remain uninjected.

To better understand the above statement lets take an example :
There are two bean A and B and both depends on each other.

Case 1: With Constructor Injection

A.java
public class A {

   B b;               // Bean property
 
   public A(B b) {
      this.b = b;    // Constructor Injection
   }
}

B.java
public class B {

   A a;               // Bean property
 
   public B(A a) {
      this.a = a;    // Constructor Injection
   }
 public static void main(String[] args) {
     ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring-Core.xml");
     Hello hello = (Hello)ctx.getBean("hello");
  
 } 
}

Spring-Core.java

<?xml version="1.0" encoding="UTF-8"?>
<beans 
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="a" class="com.def.A" autowire="constructor">
</bean>

<bean id="b" class="com.def.B" autowire="constructor">
</bean>

</beans>

Explanation: 
1. Read the first bean tag in XML file and found one dependencies of bean B. 
2. Try to get the instance of bean B but not running in the Spring Container.
3. Try to create the instance by reading the bean definition of B.
4. But again found the dependency of A on B. 
5. Now Container try to get the instance of bean A ( Which already have dependency ) . 
6. Like this it will form infinite loop and at last one bean will be injected by avoiding the Cyclic chaining.   

Note: This happens all because in case of Constructor Injection
1. Container first inject the dependencies.
2. Then create the instance of the current bean. 

So in the above condition it both the bean cannot be injected and hence non of the instance will be created and hence form the Cyclic Dependency but to avoid Cyclic dependencies , container create the instance of second bean by calling the default constructor. 

Case 2: With Setter Injection

A.java
public class A {

   B b;               // Bean property
 
   public setA(B b) {
      this.b = b;    // Constructor Injection
   }
}

B.java
public class B {

   A a;               // Bean property
 
   public setB(A a) {
      this.a = a;    // Constructor Injection
   }
 public static void main(String[] args) {
     ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring-Core.xml");
     Hello hello = (Hello)ctx.getBean("hello");
  
 } 
}

Spring-Core.java

<?xml version="1.0" encoding="UTF-8"?>
<beans 
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="a" class="com.def.A" autowire="byType">
</bean>

<bean id="b" class="com.def.B" autowire="byType">
</bean>

</beans>

Explanation: 

1. Read the first bean tag in XML file and found one dependencies of bean B. 

2. Container create the instance of A and try to inject the dependencies. 

2. So try to get the instance of bean B to Inject the bean property but not running in the Spring Container.
3. Then try to create the instance by reading the bean definition of B.
4. Again found the dependency of A on B and again before injecting the dependencies on B, first create the instance of B.  
5. Now Container try to inject the A's bean property because its instance is available . 
6. And finally Instance B is also available and inject the bean property of B.  

Note: This happens all because in case of Setter Injection
1. Container first create the instance of the current bean 
2. Then Inject the dependencies if any.  

So like this no chance of having any Cyclic Dependency in Setter Injection because of creating the current bean instance first, so anyhow a bean instance will be available to inject the bean properties.


In Spring wiring means configuration the bean dependency if any. It may be done explicitly by hard-coding the code in XMl file or implicitly by mentioning the required type of autowiring process in the XML file. Autowiring process is further divided into two category :
1. XML based Auto-Wiring process.
2. Annotation based Auto-Wiring process.

Explicitly wiring the dependencies in the XML is otherwise also called as XML based Explicitly Wiring.

XML based Auto-Wiring process 
There are four type by which we can achieve XML based autowiring, i.e
1. byName autowiring 
2. byType autowiring 
3. constructor autowiring 
4. Autodetect autowiring 

All the above auto-wiring process can be done by writing the respective values to the autowire attribute in the XML file. Like this,

<bean id=" " class=" " autowire="xxx" />
xxx can be :

a. byName         b. byType        c. constructor         d. autodetect

Annotation based Auto-Wiring
There are two annotations facility available in the Spring for bean dependency detection and injection. Injecting the bean through annotation based wiring is knows as Field Injection.
We are writing annotation with the field attributes that why it is named as Field Injection.

The two types of Annotation based Auto-Wiring are :
1. @Autowired annotation.
2. @Resource annotation.



It is a type of auto-wiring in which the injection procedure may be constructor or setter injection , depends on the argumented constructor is there in the bean. Container gives priority for the constructor injection and search for any argumented defined in the bean for injecting the bean property , if yes then injected and if not then setter injection is used for injecting the bean property. 

Autodetect wiring process is not in the Spring 3.0 as it doesn't have any additional features. Autowire attributes the value " autodetect " to use the facility for its injecting procedure. 

Container steps for Autodetect wiring prcoess.
1. Container checks for the instance running.
2. If not then search its bean definition and create the bean instance.
3. If yes then search for its matching constructor , if found then inject the bean property using Constructor Injection.
4. If not found then search for setter method, if found then inject the bean property using setter Injection with byType matching procedure.
5. If no bean found then bean property will remain uninjected.
6. If neither found matching constructor or matching setter method then also bean property will remain uninjected.

Example of constructor type autowire :
Let suppose there are two beans A and Hello and Hello is having on dependency i.e A .

Hello.java
public class Hello {
 
 A a;
  
   public Hello(A a) {
      this.a = a;
   }
 
   public static void main(String[] args) {
     ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring-Core.xml");
     Hello hello = (Hello)ctx.getBean("hello");
  
 } 
}

Spring-Core.java

<?xml version="1.0" encoding="UTF-8"?>
<beans 
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="a" class="com.def.A">
   <constructor-arg value="10"></constructor-arg> // Value of x
</bean>

<bean id="hello" class="com.def.Hello" autowire="autodetect">
</bean>

</beans>


By Constructor :

A.java
public class A {

   int x;            // Bean property
 
   public A(int x) {
      this.x = x;    // Constructor Injection
   }
}


By Setter : 

A.java
public class A {

   int x;               // Bean A Property
 
   public setA(int x) {
     this.x = x;        //Setter Injection
   }
}

Note:
In autodetect process :
* Container first checks for Constructor and if found any matching constructor then inject bean property using Constructor Injection.
* If not found any matching constructor then search for setter method and if found inject the bean property using the setter injection.


In this type of implicit wiring, container detect the bean instance and matches by its type with the type of the bean in the XML and then identifies the matching constructor to inject the bean dependencies.
Here the autowire value will be " constructor ".

Some task performed by the the Container :
1. Container checks for any instance running.
2. If its not running then try to create the instance by reading its bean definition in the XML.
3. If its running then matched its type with the class name hard-coded in the class attribute in the XML file.
4. Depending on the availability of the matched bean instances, identifies the matching constructor.
5. If found the matching constructor then inject the bean dependencies through constructor Injection.
6. If not found then then bean property will remain uninjected.
7. If exactly one bean found with its matching type and without matching constructor then bean property will remain uninjected.
8. If two beans found with its matching type then
     a. Container will try to collect one bean based on byName autowire process.
     b. If not found even with byName process then the bean property will remain uninjected.

Example of constructor type autowire :
Let suppose there are two beans A and Hello and Hello is having on dependency i.e A .

A.java
public class A {

   int x;            // Bean property
 
   public A(int x) {
      this.x = x;    // Constructor Injection
   }
}

Hello.java
public class Hello {
 
 A a;
  
   public Hello(A a) {
      this.a = a;
   }
 
   public static void main(String[] args) {
     ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring-Core.xml");
     Hello hello = (Hello)ctx.getBean("hello");
  
 } 
}

Spring-Core.java
<?xml version="1.0" encoding="UTF-8"?>
<beans 
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="a" class="com.def.A">
   <constructor-arg value="10"></constructor-arg> // Value of x
</bean>

<bean id="hello" class="com.def.Hello" autowire="constructor">
</bean>

</beans>


Note :
* Bean will be instantiated using matching constructor.
* Dependent bean instances will be detected using bean data types.
* Detected bean instance will be injected through constructor injection.





In this type of implicit wiring, container detect the bean instance and matches its name with the value of the id attribute as hard-coded in the XML file with the bean tag.

Some task performed by the the Container :
1. Container check for any bean instance running.
2. If not then try to load and create the instance of bean by finding its bean definition in the XML.
3. If yes, then try to match its name with the value of the " id " attribute hard-coded in the XML.
4. If the Bean name matches with the "id" value then it will inject the dependencies.
5. If not matched then non of the dependencies will be injected using Setter Injection.

Example of byName :
Let suppose there are two beans A and Hello and Hello is having on dependency i.e A .

A.java
public class A {

   int x;                  //Bean A property
 
   public setA(int x) {   //Setter Injection
      this.x = x;
   }
}

Hello.java
public class Hello {
 
   A a;             // Dependent bean
  
   public Hello(A a) {
      this.a = a;
   }
 
   public static void main(String[] args) {
     ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring-Core.xml");
     Hello hello = (Hello)ctx.getBean("hello");
  
 } 
}

Spring-Core.java
<?xml version="1.0" encoding="UTF-8"?>
<beans 
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="a" class="com.def.A">
   <constructor-arg value="10"></constructor-arg> // Value of x
</bean>

<bean id="hello" class="com.def.Hello" autowire="byName">
</bean>

</beans>


Note : id value i.e " a " is being matched with the instance type of bean A which is defined in the Hello bean as a reference type. 


In this type of auto-wiring container detect the bean instance with its data type and checks the data type of the bean instance running in the container with the bean type mentioned in the dependency bean.

Some of the task performed by the Container

1. It checks whether the instance of the dependent bean is running in the container or not.
2. If not then try to load the class and create the instance by searching for its bean definition in the XML file.
2. If running then try to match its type with that bean definition ( with its class name ).
3. If bean type matched with the instance type then it will be injected.
4. If found two instance of the type is running then throw exception i.e ,
" UnsatisfiedDependencyException "
5. Exactly one bean of its type will be injected through setter injection.
6. If no bean definition found with the matching type then the property of the bean remain uninjected.

Example of byType wiring :

Let suppose there are two class A and Hello. Hello is having one dependency i.e A.

A.java
public class A {

   int x;      // Property of A
 
   public setA(int x) {
     this.x = x;        //Setter Injection
   }
}

Hello.java
public class Hello {
 
  A a;             // Dependency 
  
  public Hello(A a) {
 
     this.a = a;
  }
 
  public static void main(String[] args) {
   ApplicationContext ctx=new ClassPathXmlApplicationContext("Spring-Core.xml");
   Hello hello = (Hello)ctx.getBean("hello");
  
  } 
}

Spring-Core.java

<?xml version="1.0" encoding="UTF-8"?>
<beans 
  xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="a" class="com.def.A">
   <constructor-arg value="10"></constructor-arg> // Value of x
</bean>

<bean id="hello" class="com.def.Hello" autowire="byType">
</bean>

</beans>

Note : Type of the instance running in the container i.e A here is being matched with the dependency bean name, i.e from the class attribute.


The term auto itself says half the meaning of this wiring, that the things are done implicitly without the hard-coding any thing. Wiring defines the process of injection of the dependencies of the bean. So in Auto Wiring we are not hard-coding the process by which Container will be injecting the dependencies. We are just indicating the container to do the injection by writing something in the xml file using " autowire " attribute. Autowire is an attribute of the < bean > tag and has four different values. We have four different ways by which we can wire the dependencies and containers have four different ways to inject the dependencies. They are :
1. byName
2. byType
3. constructor
4. autodetect  ( Not in Spring 3.0 )  

byName and byType ---> Setter Injection.
constructor                ---> Constructor Injection.
autodetect                 ---> Setter or Constructor Injection.

Syntax for using autowire : 
<bean id=" " class=" " autowire="xxx" /> 

byName 

In this type of auto-wiring the bean should be detected by the container using the name of the reference of the dependent bean, which must be hard-corded with its bean definition in the " id " attribute.

Its not a good idea because its again hard-coding the name and there may chance of human error. 

More about byName with examples

byType
In this type of auto-wiring the bean should be detected by the container using the declared reference type of the dependent bean.

Its better than byName type auto-wiring.

More about byType with examples

Constructor 
In this type of auto-wiring the bean should be detected by the container matching the type of the instance running in the container with the data type mentioned in the dependent bean with the reference. 

More about constructor with examples

Autodetect 
It is a type of auto-wiring in which there may be chance of injecting the dependency either by constructor or by setter method. All depends on whether any constructor is defined in the dependent bean. If yes then inject through constructor otherwise through setter method.So it gives first priority to the constructor injection. 

More about Autodetect with examples



Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic