Case 3 - Using @Required

While developing the code, the business logic will fail if the correct values are not provided, or if those are absent. So, it's a must to have the dependency injected, and whatever happens, it should not fail. To make sure that the dependency is injected and ready for use, apply @Required after the @Autowired annotation. It works in the same way as autowired=true. However, in contrast to it, the annotation can be applied only to the setter methods. If the dependency is not available, BeanInitializationException will be thrown.

The following code gives us a clear understanding of the use of @Required annotation:

@Component(value="cust_required") 
Public class Customer_Annot_Required { 
  private String cust_name; 
  private int cust_id; 
 
  private Address cust_address; 
 
  public void setCust_name(String cust_name) { 
   this.cust_name = cust_name; 
  } 
 
  public void setCust_id(intcust_id) { 
   this.cust_id = cust_id; 
  } 
 
  @Autowired 
  @Required 
  public void setCust_address(Address cust_address) { 
   this.cust_address = cust_address; 
  } 
 
  public Customer_Annot_Required() { 
    // TODO Auto-generated constructor stub 
    cust_id=10; 
    cust_name="my name"; 
  } 
  // getter methods 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.104.120