Using bean reference

Each bean configured in the XML has its unique bean id. This can be used to refer to the value or autowiring using SpEL. Use the following steps to understand how to use bean reference:

  1. In the preceding Ch02_SpringEL project, add a new POJO class as Address and Customer_Reference in com.ch02.beans, as shown in the following piece of code:
public class Address { 
  private String city_name; 
  private int build_no; 
  private long pin_code; 
 
  // getter and setter 
  @Override 
  public String toString() { 
    // TODO Auto-generated method stub 
    returncity_name+ ","+pin_code; 
  } 
} 
public class Customer_Reference { 
  private String cust_name; 
  private int cust_id; 
  private Address cust_address; 
 
  // getter and sertter 
 
  @Override 
  public String toString() { 
    return cust_name + " is living at " + cust_address; 
  } 
} 
  1. Add Address and Customer_Reference beans in beans.xml, as follows:
<bean id="cust_address" class="com.ch02.beans.Address"> 
  <property name="build_no" value="2"/> 
  <property name="city_name" value="Pune"/> 
  <property name="pin_code" value="123"/> 
</bean> 
<bean id="cust_ref" class="com.ch02.beans.Customer_Reference"> 
  <property name="cust_name" value="Bina"/> 
  <property name="cust_id" value="#{2}"/> 
  <property name="cust_address" value="#{cust_address}"/> 
</bean> 

Observe the way cust_address is initialized. The customer's address is placed value as cust_address, which is the id of the bean defined for Address.

  1. Define TestCustomer_Reference, as we did in Step 4 of the previous case, to get the cust_ref bean.
  2. On execution, we will get the following output:
  1. Sometimes, instead of using the bean, we may want to inject only one of the properties of the bean, as shown in the following piece of code:
<bean id="cust_ref_new" class="com.ch02.beans.Customer_Reference"> 
  <property name="cust_name" 
    value="#{cust_ref.cust_name.toUpperCase()}"/> 
  <property name="cust_id"value="#{2}"/> 
  <property name="cust_address"value="#{cust_address}"/> 
</bean> 

We injected cust_name by borrowing it from the cust_ref bean and converting it to uppercase.

..................Content has been hidden....................

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