Case 2 - Using autowired=false

Whatever care the developers take, we will always come across scenarios where the dependency is not available, or doesn't get injected due to some reason. It's quite obvious to get an exception here. In order to get rid of such a forceful injection, we will add required=false to @Autowired. To find its effect, follow these steps, keeping the class definition as it is:

  1. You can try this out by deleting cust_address from customer.xml in the previous project. On execution of main, we will get the following exception:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ch02.beans.Address] found for dependency [com.ch02.beans.Address]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired 
(required=true)} 
  1. Now, change the @Autowired annotation to the following lines of code:
@Autowired(required=false) 
private Address cust_address; 
  1. Again, rerun the main function from the previous code. You will get the following output:

The null value that denotes no address is injected, but we haven't got any bean creation exception here.

Once you finish the demonstration of required=false, undo all the changes you just made in this demo.
..................Content has been hidden....................

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