如何在春季的二传手注射中使用@Required注释?

时间:2015-12-30 10:20:14

标签: java spring dependency-injection

@required注释用法。我尝试使用上面的setter方法并尝试从上下文中查找bean而不设置此依赖项。我得到了依赖项设置为null的对象,我的期望是spring会抛出一些异常。请指导我在哪里做错了?

2 个答案:

答案 0 :(得分:0)

@Required to make it mandatory that the dependency has to be injected

让我们举个例子: 我们需要使用RequiredAnnotationPostProcessor来检查是否已注入@Required个依赖项

public class BankService {
  private CustomerService customerService;
  private BillPaymentService billPaymentService;
  @Required
  public void setCustomerService(CustomerService customerService) {
   this.customerService = customerService;
  }
  @Required
  public void setBillPaymentService(BillPaymentService billPaymentService) {
  this.billPaymentService = billPaymentService;
}
}

配置就像

<bean id="custService" class="xml.CustomerServiceImpl" />
<bean id="billingService" class="xml.BillPaymentServiceImpl" />
<bean id="bankService" class="xml.BankServiceImpl">
 <property name="customerService" ref="custService" />
 <property name="billPaymentService" ref="billingService" />
</bean>
<bean class=”o.s.beans.factory.annotation.RequiredAnnotationBeanPostProcessor" />

如果我们不设置这两个属性,我们将收到BankService配置的错误,因为它们都是@Required。

我希望这会有所帮助!!

答案 1 :(得分:0)

$request = new Facebook\FacebookRequest(
$session,
'GET',
'/me/friends'
);
echo 'hi1';
$response = $request->execute();
echo 'hi2';
$graphObject = $response->getGraphObject();
echo 'hi3';