@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 propertiespublic 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"); } }
A a;
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.
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.
EmoticonEmoticon