Sunday, 13 April 2014

Spring IoC : Annotation on Constructor

Advertisement

@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.


EmoticonEmoticon