• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to specify Spring Bean Reference and Spring Inner Bean

May 24, 2016 by javainterviewpoint Leave a Comment

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:

  1. Create a new Java Project  “SpringCoreTutorial” and create a package for our src files “com.javainterviewpoint“
  2. 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

  3. Create the Java classes Employee.java and PermanentEmployee.java under  com.javainterviewpoint folder.
  4. 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 :

Spring Bean Reference Example

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>

Other interesting articles which you may like …

  • Spring 3 Hello World Example
  • Spring 3 JavaConfig Example
  • Spring 3 @Import annotation with JavaConfig Example
  • Dependency Injection In Spring
  • Spring Dependency Injection – Setter Injection
  • Spring Setter Injection With Primitive data types
  • Spring Dependency Injection With List Collection Example
  • Spring Dependency Injection With Set Collection Example
  • Spring Dependency Injection With Map Collection Example
  • Spring Dependency Injection With Properties Example
  • Spring Difference between Setter and Constructor Injection
  • Spring Bean Scopes Example
  • Autowiring in Spring
  • Spring Autowiring byName Example
  • Spring Autowiring byType Example
  • Spring Autowiring constructor Example

Filed Under: J2EE, Java, Spring, Spring Core, Spring Tutorial Tagged With: Spring Bean Reference, Spring Inner Bean

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·