Now that you know how to set primitives, let's do the coding for reference configuration as well. We will use the same DI_using_namespace project to develop the code further:
- Copy or create an Address class (refer to the code from Ch02_Reference_DI) in the com.ch02.beans package.
- Copy or create a Customer class (refer to the code from Ch02_Reference_DI) in the com.ch02.beans package.
- Add a bean for Address using setter DI in beans.xml.
- Add a bean for Customer using namespace p, and the configuration will look like the following code:
<bean id="customer" class="com.ch02.beans.Customer" p:cust_id="2013" p:cust_name="It's Bob" p:cust_address-ref="cust_address"> </bean>
You can observe here that the customer address is not primitive, so, instead of using value, we use the reference as p:cust_address-ref ="cust_address', where cust_address is the id representing the Address bean.
- Create TestCustomer with the main function containing the following code:
public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml"); Customer customer=(Customer)context.getBean("customer"); System.out.println(customer.getCust_name()+" "+ customer.getCust_id()); }
- The execution of code will show the following output: