上QQ阅读APP看书,第一时间看更新
@Autowired with required = false
By default, the @Autowired annotation implies that the dependency is required. This means an exception will be thrown when a dependency is not resolved. You can override that default behavior using the (required=false) option with @Autowired. Let's see the following code:
public class BankingService {
private CustomerService customerService;
@Autowired (required=false)
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
......
}
In the previous code, if we set the required value as false, then at the time of bean wiring, Spring will leave the bean unwired if the dependency is not resolved. As per Spring's best practices, we should avoid setting required as false until it is absolutely required.