上QQ阅读APP看书,第一时间看更新
Setter-based DI
In a constructor-based DI, we saw a dependent object injecting through a constructor argument. In a setter-based DI, the dependent object is provided by a setter method in the dependent class. Setter-based DI is accomplished by calling setter methods on beans after invoking no-args constructors through the container.
In the following code, we show how to use a setter method for injecting a CustomerService object in the BankingService class:
@Component
public class BankingService {
private CustomerService customerService;
// Setter-based Dependency Injection
@Autowired
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
public void showCustomerAccountBalance() {
customerService.showCustomerAccountBalance();
}
}