Example of @Autowired (setter injection approach 2)

In this post under Spring Core, I will show another approach of achieving setter injection using “@Autowired” annotation.

In my previous posts, I showed with example how to achieve setter injection by applying “@Autowired” annotation at field level.

In this post I will show how to achieve setter injection by applying “@Autowired” annotation directly on setter methods.

For our example we create two bean classes

Bean1 class

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

In the above class structure, “Bean1” class is dependent on “Bean2” class and I am telling Spring framework to inject “Bean2” instance to “Bean1” instance by calling setter method of “Bean1” instance.

I am telling this to the Spring framework by applying the “@Autowired” annotation at setter method level.

In this way, we can inject dependee beans to dependent beans.

Below is the other classes for your reference

Bean2 class

package package19;

import org.springframework.stereotype.Component;

@Component
public class Bean2 {

}

Below is the main class for your reference

Main class

package package19;

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

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

Leave a Reply