Example of @Autowired (setter injection approach 1)

In this post under Spring Core, I will explain with example the purpose and how to use “@Autowired” annotation.

Till now in all my previous posts, you have seen how to create a bean.

We can create a bean using either “@Bean” or “@Component” annotation.

I have also showed you how to wire one “@Bean” annotated component as a dependency into another bean manually through constructor and setter injection.

But never shown you how to let Spring framework does that injection automatically. That is where “@Autowired” annotation comes it to picture.

I will demonstrate with example.

For our example I will create two beans annotated with “@Component” as shown below

Bean structure

1  package package17;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.stereotype.Component;
5
6 @Component
7 public class Bean1 {
8 @Autowired
9 private Bean2 bean2;
10
11 public Bean2 getBean2() {
12 return bean2;
13 }
14
15 public void setBean2(Bean2 bean2) {
16 this.bean2 = bean2;
17 }
18 }
19
20 package package17;
21
22 import org.springframework.stereotype.Component;
23
24 @Component
25 public class Bean2 {
26
27 }

As you can see from above code snippet, I have created two “@Component” annotated beans.

You can also see “Bean1” is dependent on “Bean2”.

To tell the Spring framework to inject “Bean2” as a dependent into “Bean1”, we annotate the “Bean2” field declaration in “Bean1” class with “@Autowired” annotation. Refer to line 9.

Spring framework processes the annotation and injects “Bean2” instance into “Bean1” field with name “bean2” by calling its setter method.

By default “@Autowired” annotation inject beans based on bean type.

So in this case, since field “bean2” type is “Bean2”. Spring framework creates an instance of “Bean2” and set it to “bean2” field.

In this way we can use “@Autowired” annotation.

Below is the main class for your reference.

Main class

package package17;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "package17")
public class Example17 {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example17.class);
Bean1 bean1 = applicationContext.getBean(Bean1.class);
System.out.println(bean1.getBean2());
}
}

Leave a comment