Mastering Spring 5.0
上QQ阅读APP看书,第一时间看更新

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:

    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:

    public class BusinessServiceImpl { 
@Autowired
private DataService dataService;
}