[Recipe] Basic Spring Program Using XML Configuration

Problem: 

Create a basic spring program from scratch using XML configuration. 

Solution Summary: 

We will create a simple class, configure it and test it. You can configure a Spring application through xml, or Java configuration or annotations along with xml or java configuration. In this example, we will see the use of xml for Spring configuration. There are notes for other two approaches as well.

Prerequisites: 

If you are using Maven, just copy paste below dependency into your pom file and all other required dependencies will be added automatically, as they are the transitive dependencies for below dependency.

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.2.6.RELEASE</version>
    </dependency>
</dependencies>

Please use the latest version as available in the Spring website @ http://projects.spring.io/spring-framework.

Though not required for this example, you may also add dependency for spring-test and junit, and also set the compiler level to java 8. By defalt maven may use java 5.

PS: There is a separate note for getting started with Gradle build, but notes in this section will be using Maven build tool in general. 

Solution: 

We will create a simple class, JJWriter.java, with a single method write. This class is a regular pojo (plain old java object) class with no spring specific code. We will create a simple spring config file, spring.xml with a simple bean definition to configure the class as a bean; and then test all these together using a simple test class,  JJWriterMain.java. Note that the name of the config file can be anything. 

 

Example Code

JJWriter.java

The JJWriter.java has a single method write:

package com.javajee.spring;

public class JJWriter {

  public void write() {

    System.out.println("Default Writer");

  }

}

 

The spring.xml file

The spring config xml spring.xml has a bean definition for JJFileWriter: 

<?xml version="1.0" encoding="UTF-8"?>

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

               <bean id="jjwriter" class="com.javajee.spring.JJWriter">

               </bean>

</beans>

Place this file in the classpath root (under src folder).

We will give an id to each of our bean definitions so that we can refer to it with that name from our code.

 

Note:

  • If you are copy pasting this xml structure, you might see occurences of  'External Links icon' which is due to the external links handling of this website. Replace all occurrences of 'External Links icon' with blank. It is not needed if you are seeing this xml and typing yourself.

  • Please make sure you use the right xsd. In my case, the latest is spring-beans-4.0.xsd. You can also find the xsds within your downloaded distribution under schemas folder.

 

JJWriterMain.java

The test class JJWriterMain will ask spring to create and return us an object of the class type defined using the class attribute of the bean using the bean id:

package com.javajee.spring;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

public class JJWriterMain {

  public static void main(String[] args) {

    ApplicationContext context= new ClassPathXmlApplicationContext("spring.xml");

   //JJWriter writer = (JJWriter)context.getBean("jjwriter");

  JJWriter writer = context.getBean("jjwriter", JJWriter.class);

    writer.write();

  }

}

Always use the version of getBean that also takes in the class type, as it will be more strongly typed and avoids the need for casting as in the commented code,

If you are in eclipse and if you hover over the context reference variable in the declaration line, you will see a warning that: Resource leak: 'context' is never closed.  We will see the reason and also see how to fix in another note.

 

Executing the program

If you run this program now, you can see the output as:

Default Writer

 

We will see in coming tutorials ways to improve this program by coding to interfaces and changing dependency through config files.

Recipe Tags: 

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) ArrayLists (1) Arrays (2) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (52) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (4) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (7) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (8) Javascript Frameworks (1) Java SE Professional (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) resources (1) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)