• 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

Spring XML Configuration Example

December 6, 2018 by javainterviewpoint Leave a Comment

In this Spring XML Configuration Example, we will be creating a simple spring application using the spring xml configurations which displays Book and Library details and we will also be injecting book reference into library class.


Spring XML Configuration Example

Folder Structure:

Spring XML Configuration Example 1

  1. Create a simple Maven webapp Project “SpringCoreExample” and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the POM.xml
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.javainterviewpoint</groupId>
      <artifactId>SpringCoreExample</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>jar</packaging>
    
      <name>SpringCoreExample</name>
      <url>http://maven.apache.org</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
         <spring.version>5.1.1.RELEASE</spring.version>
      </properties>
    
      <dependencies>
         <!-- Spring Dependencies -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
      </dependencies>
    </project>
  3. Create the Java class Application.java, Book.java and Library.java under  com.javainterviewpoint folder.
  4. Place the SpringConfig.xml under src/main/java folder

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 Setter Injection With Objects
  • Spring Dependency Injection With List Collection Example
  • Spring Dependency Injection With Set Collection Example
  • Spring Dependency Injection With Map Collection Example
  • Spring @Autowired, @Resource, @Qualifier, @Inject Annotation
  • Spring @Required Annotation
  • Spring Bean Life Cycle – Bean Initialization and Destruction
  • Spring Bean Creation – Static & Instance Factory Method
  • Spring PropertyPlaceholderConfigurer Example
  • How to Instantiate Spring IoC Container
  • Spring Dependency Injection With Properties Example

Spring XML Configuration Example

Dependency Tree

[INFO] ------------------------------------------------------------------------
[INFO] Building SpringCoreExample 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:2.1:tree (default-cli) @ SpringCoreConfiguration ---
[INFO] com.javainterviewpoint:SpringCoreExample:jar:0.0.1-SNAPSHOT
[INFO] +- org.springframework:spring-core:jar:5.1.1.RELEASE:compile
[INFO] |  \- org.springframework:spring-jcl:jar:5.1.1.RELEASE:compile
[INFO] +- org.springframework:spring-beans:jar:5.1.1.RELEASE:compile
[INFO] \- org.springframework:spring-context:jar:5.1.1.RELEASE:compile
[INFO]    +- org.springframework:spring-aop:jar:5.1.1.RELEASE:compile
[INFO]    \- org.springframework:spring-expression:jar:5.1.1.RELEASE:compile
[INFO] ------------------------------------------------------------------------

Book.java

Book class is a simple class consisting of the book details such title, author, publications and its corresponding POJO’s.The getBookDetails()method will display the book information which is set.

package com.javainterviewpoint;

public class Book
{
    private String title;
    private String publications;
    private String author;

    public Book()
    {
        super();
    }

    public Book(String title, String publications, String author)
    {
        super();
        this.title = title;
        this.publications = publications;
        this.author = author;
    }
    
    public String getTitle()
    {
        return title;
    }

    public void setTitle(String title)
    {
        this.title = title;
    }

    public String getPublications()
    {
        return publications;
    }

    public void setPublications(String publications)
    {
        this.publications = publications;
    }

    public String getAuthor()
    {
        return author;
    }

    public void setAuthor(String author)
    {
        this.author = author;
    }

    public void getBookDetails()
    {
        System.out.println("**Published Book Details**");
        System.out.println("Book Title        : " + title);
        System.out.println("Book Author       : " + author);
        System.out.println("Book Publications : " + publications);
    }
}

Library.java

Library class has the Book class instance as a property and its corresponding getters and setters. The book property will get its value through our configuration file.

package com.javainterviewpoint;

public class Library
{
    private Book book;

    public void setBook(Book book)
    {
        this.book = book;
    }

    public Book getBook()
    {
        return book;
    }
}

SpringConfig.xml

In our configuration file we have defined seperate id for each bean Library and Book classes

<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-3.0.xsd">

    <bean id="library" class="com.javainterviewpoint.Library">
         <property name="book" ref="book"></property>
    </bean>
 
    <bean id="book" class="com.javainterviewpoint.Book">
         <property name="title" value="Spring XML Configuration"></property>
         <property name="author" value="JavaInterviewPoint"></property>
         <property name="publications" value="JIP Publication"></property>
     </bean>
</beans>
  • We inject primitives to the Book class properties such as title, author, publications.
    <bean id="book" class="com.javainterviewpoint.Book">
             <property name="title" value="Spring XML Configuration"></property>
             <property name="author" value="JavaInterviewPoint"></property>
             <property name="publications" value="JIP"></property>
     </bean>
  • We are referencing the Book class bean id to the property book of the Library class
<property name="book" ref="book"></property>
  • The ref passed to the property book should be the bean id of the Book Class. In short

ref =<<bean id of Book class>>

Application.java

package com.javainterviewpoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Application
{
    public static void main(String args[])
    {
        // Read the Spring configuration file [SpringConfig.xml]
        ApplicationContext appContext = new ClassPathXmlApplicationContext("SpringConfig.xml");
        // Get the Library instance
        Library library = (Library) appContext.getBean("library");
        // Get the Book Details
        library.getBook().getBookDetails();
    }
}
  • ApplicationContext class reads our Configuration File(SpringConfig.xml) and obtain all the bean definition mentioned in the config file.
  • The Library class instance is obtained by calling the getBean() method over the ApplicationContext.
  • The String passed to getBean() method should be equivalent to the id defined in the SpringConfig.xml
  • Since we have already injected Book object to the property book in Library class, we can display the book details by simply calling the getBookDetails() method on top of library.getBook()

Output

Dec 05, 2018 6:20:13 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org[email protected]5cb0d902: startup date [Wed Dec 05 18:20:13 IST 2018]; root of context hierarchy
Dec 05, 2018 6:20:13 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [SpringConfig.xml]
**Published Book Details**
Book Title        : Spring XML Configuration
Book Author       : JavaInterviewPoint
Book Publications : JIP Publication

Filed Under: Java, Spring, Spring Core Tagged With: Spring Configuration, Spring Core, Spring XML Configuration, Spring XML Configuration Example

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 ·