Sunday, December 25, 2016

Spring Hello World Example using XML Config

In this Spring framework tutorial, you will learn how to write the hello world example in Spring framework. This should be the first tutorial to start learning Spring framework, as it gets the ball rolling. While coding and running this example, you learn a lot about Spring framework, Spring XSD files, necessary JAR files, and more importantly how Spring framework works.This HelloWorld program in Spring framework is an extension of classical Java hello world program, written using dependency Injection design pattern by using Spring Framework's IOC container.  Even though now you can configure Spring dependency using annotations and Java configuration, this example uses traditional XML way to configure dependency.

This is important to learn because there are many Spring-based Java projects, which are live in production and still using XML configuration. If you have to maintain them, you must understand how to configure Spring dependency in the XML file.

Spring is one of the most popular Java application framework, which promotes some best practices while writing Java application e.g. dependency Injection. Spring provides an IOC container to manage life-cycle of Spring beans and provides support to get beans any time from IOC container. Apart from Spring's IOC container, it also provides rich API to simply many of Java task e.g. JdbcTemplate help you to write JDBC code without taking care of boilerplate things like closing connection, statement, resultset etc.


Similarly, Spring framework also provides JmsTemplate to simply JMS related task e.g. sending and receiving messages in Java. I first learned about the usefulness of Spring framework, while reading Expert Spring MVC and Web Flow, its first few chapters are very important to learn spring framework because they explain to you how dependency injection provides improved testing, loose coupling, and help in clean code.

Those two chapters are so far my best read on Spring, and I also suggest you take a look. By the way in this Spring tutorial, we will see one of the most simple examples of dependency Injection e.g. Hello Example. Message to Hello class is provided by Spring framework using Dependency Injection.


Spring and Java HelloWorld Example

In this example, we have created a bean or a Java class called Hello, which accepts a String message as a dependency. This spring bean is initialized using spring configuration file i.e. spring-config.xml. All beans declared in spring configuration file is created and managed by Spring IOC container.


If you look Spring configuration file, then you will find that id of the bean is "hello", which will be further used to get the reference of this bean from Spring framework using the getBean() method of ApplicationContext or BeanFactory class

In order to test this Spring HelloWorld example, we have created a Main class, which has classical public static void main(String args[]) method.  In the main method, we are creating an instance of ClassPathXMLApplicationContext by providing spring-config.xml, which must be available in the classpath, in order for Spring to initialize beans.

Next two lines of code are self-explanatory, where we are getting the reference of Hello bean by using "id" attribute of Hello bean declaration.

For printing HelloWorld in the console, Instead of using System.out.println, we have used log4j. As it's important to setup logging in every Java application because System.out.println() is not good enough for real-world Java application.

Spring 3 Hello World Example using XML Config


I have configured log4j using log4j.xml which is also available in the classpath. By the way, there are mainly two ways to inject dependency using Spring, Constructor injection, and Setter Injection, and this example uses setter injection to pass the message to Hello object.

So this Spring hello world example contains following configuration files and Java classes.

Hello.java  - Hello Bean which prints message provided to it by using spring dependency Injection
Main.java - Test class for this Spring Helloworld example
spring-config.xml  - Spring configuration file which contains bean declaration
log4j.xml - log4j configuration file

If you want to implement this example using constructor injection then you need to make a couple of changes in Hello class and Spring configuration file. Make sure your Hello class accept the String message in the constructor and when you configure that bean in Spring configuration file, instead of using property, use constructor-arg tag. You can also see Getting Started with Spring framework for a couple of example on constructor injection and writing hello world using annotation in Spring 4.0.

Spring 3 HelloWorld Example using XML Config



Required dependency JAR files
This Spring hello world example uses Spring 3.1.2.RELEASE.jar files e.g.

  • spring-core-3.1.2.RELEASE.jar
  • commons-logging-1.1.1.jar
  • log4j-1.2.16.jar
  • spring-context-3.1.2.RELEASE.jar
  • spring-aop-3.1.2.RELEASE.jar
  • aopalliance-1.0.jar
  • spring-beans-3.1.2.RELEASE.jar

In order to run this Spring hello world example, just run Main class as Java application from command line or Eclipse IDE.


Spring HelloWorld Java Class

import org.apache.log4j.Logger;

/*
 * Java class which accept message as dependency injected
 */
public class Hello {

        private static final Logger logger = Logger.getLogger(Hello.class);
        private String message;

        public void setMessage(String message) {
                this.message = message;
        }

        public String getMessage() {
                return message;
        }
      
        public void sayHello(){
                logger.info(“Hello world Spring message is:+ message);        }

}


Main Class to Test HelloWorld Bean

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

/*
 * Main class to start and test this Java application
 */
public class Main {

        public static void main(String args[]){
               ApplicationContext context = new ClassPathXmlApplicationContext(
                                                "spring-config.xml");
                Hello hello = (Hello) context.getBean("hello");
                hello.sayHello();
        }
}


log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

        <appender name="console" class="org.apache.log4j.ConsoleAppender" >
            <layout class="org.apache.log4j.PatternLayout">
                 <param name="ConversionPattern" value="%d %-4r [%t] %-5p %c %x - %m%n" />
            </layout>
        </appender>

        <logger name="org.springframework" >
             <level value="ERROR" />
             <appender-ref ref="console" />
        </logger>

        <logger name="org.apache">
             <level value="DEBUG" />
             <appender-ref ref="console" />
        </logger>

        <root>
             <level value="DEBUG" />
             <appender-ref ref="console" />
        </root>
</log4j:configuration>



Spring Configuration File spring-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

        <bean id="hello" class="Hello">
                <property name="message" value="Good Afternoon" />
        </bean>

</beans>


Output
Hello world Spring message is: Good Afternoon


That's all on this Spring and Java HelloWorld Example using dependency Injection. For a Java programmer, knowledge of Spring framework is quickly becoming from good to have, to must have and it's high time to learn and use Spring framework while writing Java applications. Initially, it takes some time to get used of XML and Spring configuration file, various spring releases and JAR files and Spring API. Once you get hold of basics of Spring framework and dependency Injection design principle, writing Java program in Spring framework is real fun. In the next part of this tutorial, You will learn how to write Spring hello world using annotations and Java configuration, so stay tune and till then enjoy the life. 


Further Learning
Spring Fundamentals Course
Introduction to Spring MVC 4
Spring in Action 4th Edition 

P.S. - If you want to learn how to develop RESTful Web Service using Spring MVC in depth, I suggest you join the REST with Spring master class by Eugen Paraschiv. One of the best course to learn REST with Spring MVC. 

2 comments :

Gauri said...

Hello, Can you please also post Spring hello world example using Annotation? I am familiar with XML config file but really struggle with using annotation in Spring. please help.

Learning Spring by Self Study said...

Thank you so much for this step by step guide to create Spring Helloworld program in Eclipse. Am I right to assume that you are using Setter dependency injection here? If yes, Can you please suggest how we can use the Constructor injection here?

Post a Comment