Setter injection example with more than one argument (@Autowired)

In this post under Spring core, I explains how to instruct Spring framework to call a setter method (which take more than one argument) while creating a bean.

In most of the cases, the setter methods of a class takes only one argument but if a case arises where a setter method has to take more than one argument, the below approach will help developers.

For our example, I will use a manager class which uses two dao classes. The dao classes are to be injected into the manager class as dependencies.

Instead of using separate setters for each dao, I will use one setter method, which takes instances of both dao classes as parameters as shown below.

Manager

1  package package21;
2
3 import org.springframework.beans.factory.annotation.Autowired;
4 import org.springframework.stereotype.Component;
5
6 @Component
7 public class Manager {
8 private Dao1 dao1;
9 private Dao2 dao2;
10
11 @Autowired
12 public void setDao(Dao1 dao1, Dao2 dao2) {
13 this.dao1 = dao1;
14 this.dao2 = dao2;
15 }
16
17 public Dao1 getDao1() {
18 return dao1;
19 }
20
21 public Dao2 getDao2() {
22 return dao2;
23 }
24 }

As you can see from the above code, I have the manager class that is dependent on two dao classes.

From line 11 to 15, I have created one setter method which takes both dao instances as arguments.

Below are the class structure of dao classes

Dao1 class

package package21;

import org.springframework.stereotype.Component;

@Component
public class Dao1 {
}

Dao2 class

package package21;

import org.springframework.stereotype.Component;

@Component
public class Dao2 {
}

In this way we can create a setter method which takes more than one argument and Spring Framework will take care of injecting the dependencies.

Below is the main code for your complete reference

Main class

package package21;

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

@ComponentScan(basePackages = "package21")
public class Example21 {
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example21.class);
Manager manager = applicationContext.getBean(Manager.class);
System.out.println("manager.getDao1(): " + manager.getDao1());
System.out.println("manager.getDao2(): " + manager.getDao2());
}
}

Leave a Reply