If you are using Setter Injection or Constructor Injection to inject a simple data type then we will be using the <value> tag in the bean configuration file to inject. Whereas when we want to refer another bean then we have to use <ref> tag. Lets see how we can refer another bean in this Spring bean reference example.
Spring Bean Reference Example
Folder Structure:
- Create a new Java Project “SpringCoreTutorial” and create a package for our src files “com.javainterviewpoint“
- Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.
commons-logging-1.2.jar
spring-beans-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar - Create the Java classes Employee.java and PermanentEmployee.java under com.javainterviewpoint folder.
- Place our configuration file SpringConfig.xml in the src directory
Bean Classes
Employee.java
package com.javainterviewpoint; public class Employee { public String name; public int age; public Employee() { super(); } public Employee(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Employee [name=" + name + ", age=" + age + "]"; } }
PermanentEmployee.java
package com.javainterviewpoint; public class PermanentEmployee { private Employee employee; private int Salary; public PermanentEmployee() { super(); } public PermanentEmployee(Employee employee, int salary) { super(); this.employee = employee; Salary = salary; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public int getSalary() { return Salary; } public void setSalary(int salary) { Salary = salary; } }
Our PermanentEmployee class has Employee class as one of the property, for which we will be refering the bean through our configuration file.
Declaring Bean Configuration File (SpringConfig.xml)
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="e" class="com.javainterviewpoint.Employee">
<property name="name" value="JavaInterviewPoint"></property>
<property name="age" value="999"></property>
</bean>
<bean id="pe" class="com.javainterviewpoint.PermanentEmployee">
<property name="employee">
<ref bean="e"></ref>
</property>
<property name="salary" value="1000000"></property>
</bean>
</beans>
- We have declared the two bean ids “e”, “pe” for Employee and PermanentEmployee class respectively.
- Through Spring Setter Injection we have injected the values to the property of both the beans.
- Using the <ref> tag we have referred the “Employee” class to the “employee” property of PermanentEmployee class. When Spring IoC Container encounters this line it searches for the bean with the id “e” and if found it injects it for the property “employee”.
Instantiating Spring IoC Container Using Application Context
Since ApplicationContext is an interface, Here we need to instantiate an implementation of it. We will instantiate ClassPathXmlApplicationContext implementation which builds an application context by loading an XML configuration file from the classpath.
package com.javainterviewpoint; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class EmployeeLogic { public static void main(String args[]) { //Read the Configuration file using ApplicationContext ApplicationContext applicationContext = new ClassPathXmlApplicationContext("SpringConfig.xml"); //Get the PermanentEmployee class instance PermanentEmployee pe = (PermanentEmployee) applicationContext.getBean("pe"); //Print the PermanentEmployee details System.out.println("**** Permanent Employee Details ****"); System.out.println("PermanentEmployee Name : "+pe.getEmployee().getName()); System.out.println("PermanentEmployee Age : "+pe.getEmployee().getAge()); System.out.println("PermanentEmployee Salary: "+pe.getSalary()); } }
- In our EmployeeLogic class we have read the Configuration file(SpringConfig.xml) and get all the bean definition through ApplicationContext
- Get the PermanentEmployee Class instance by calling the getBean() method over the context created.
- Since we have referred the Employee bean for the employee property of PermanentEmployee class in our configuration file, we can call the method on top of it.
Output :
Usage of “local”
The bean name mentioned in the <ref> element’s bean attribute can be a reference to any bean in the IoC container, even if it’s not defined in the same XML configuration file. When we are referring to a bean in the same XML file, we should use the local attribute, as it is an XML ID reference. This will help the XML editor to validate if the bean exist in the same XML file or not.
<bean id="e" class="com.javainterviewpoint.Employee"> <property name="name" value="JavaInterviewPoint"></property> <property name="age" value="999"></property> </bean> <bean id="pe" class="com.javainterviewpoint.PermanentEmployee"> <property name="employee"> <ref local="e"></ref> </property> <property name="salary" value="1000000"></property> </bean> </beans>
Shortcut way of referring a bean
Instead of using the <ref> tag to refer a bean in our configuration file we can refer the bean directly by using the ref attribute of the <property> tag itself like below.
<bean id="e" class="com.javainterviewpoint.Employee">
<property name="name" value="JavaInterviewPoint"></property>
<property name="age" value="999"></property>
</bean>
<bean id="pe" class="com.javainterviewpoint.PermanentEmployee">
<property name="employee" ref="e"></property>
<property name="salary" value="1000000"></property>
</bean>
Spring p namespace bean ref
From Spring 2.x onwards there is another convenient shortcut for specifying the Spring bean reference. It’s by using the p namespace schema. It is an attribute of the <bean> element. This will be obviously minimize the number of lines in the XML configuration file. In order to use p schema we need to add it to our XML header.
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="e" class="com.javainterviewpoint.Employee" p:name="JavaInterviewPoint" p:age="111"></bean> <bean id="pe" class="com.javainterviewpoint.PermanentEmployee" p:employee-ref="e" p:salary="20000"></bean> </beans>
Specifying Spring Bean References for Constructor Arguments
Spring Bean reference can be applied for constructor injection also, in the above PermanentEmployee class we are having a constructor which the employee attribute. Lets see how we can specify Spring Bean reference for the Constructors. We will be using the <constructor-args> for Constructor Injection and add <ref> tag under it. Our configuration file can be written like below
<bean id="e" class="com.javainterviewpoint.Employee">
<constructor-arg name="name" value="JavaInterviewPoint" />
<constructor-arg name="age" value="222" />
</bean>
<bean id="pe" class="com.javainterviewpoint.PermanentEmployee">
<constructor-arg>
<ref bean="e" />
</constructor-arg>
<constructor-arg name="salary" value="999999" />
</bean>
Spring Inner Beans
Whenever a bean is used for only one purpose and not used anywhere else then it can be declared as inner beans. Inner Beans can be used within <property> tag (Setter Injection) or <constructor-arg> tag (Constructor Injection). To declare a inner beans don’t add “id” or “name” attribute to that bean in this way the bean will anonymous and cannot be used anywhere else.
<bean id="pe" class="com.javainterviewpoint.PermanentEmployee"> <property name="employee"> <bean class="com.javainterviewpoint.Employee"> <property name="name" value="JavaInterviewPoint"></property> <property name="age" value="999"></property> </bean> </property> <property name="salary" value="1000000"></property> </bean>
Leave a Reply