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

1 comment:

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic