spring_depend_injection

Two Types of Dependency injection types

1. the setter injection

The setter injection is used to inject the dependencies through setter methods. In the following example, the instance of DataService uses the setter injection:

1
2
3
4
5
6
7
 public class BusinessServiceImpl {
private DataService dataService;
@Autowired
public void setDataService(DataService dataService) {
this.dataService = dataService;
}
}

Actually, in order to use the setter injection, you do not even need to declare a setter method. If you specify @Autowired on the variable, Spring automatically uses the setter injection. So, the following code is all that you need for the setter injection for DataService:

1
2
3
4
public class BusinessServiceImpl {
@Autowired
private DataService dataService;
}

2. the constructor injection

The constructor injection, on the other hand, uses a constructor to inject dependencies. The following code shows how to use a constructor for injecting in DataService:

1
2
3
4
5
6
7
8
   public class BusinessServiceImpl {
private DataService dataService;
@Autowired
public BusinessServiceImpl(DataService dataService) {
super();
this.dataService = dataService;
}
}

When you run the code with the preceding implementation of BusinessServiceImpl, you will see this statement in the log, asserting that autowiring took place using the constructor:
Autowiring by type from bean name ‘businessServiceImpl’ via
constructor to bean named ‘dataServiceImpl’

From