Wednesday, March 6, 2019

Spring Hello World Example in Java using Dependency Injection and XML Configuration

Hello All, In this Spring framework tutorial, you will learn how to write the hello world example in the Spring framework. This should be your 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 the classical Java hello world program, which you might have seen earlier. This program is written using the Dependency Injection design pattern by using the Spring Framework's IOC container.  Even though now you can configure Spring dependency using annotations and Java configuration, this example uses a traditional XML way to configure dependencies.

This is important to learn because there are many Spring-based Java projects, which are already 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 creating a Java application like Dependency Injection and ease of testing. 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 simplify many of common Java tasks like  JdbcTemplate help you to write JDBC code without taking care of boilerplate things like closing connection, statement, resultset etc.

Similarly, the Spring framework also provides JmsTemplate to simply JMS related task like sending and receiving messages in Java.

Spring Framework is full of such goodness and that's why I suggest every Java developer who wants to learn Spring is to go through a comprehensive course like Spring Framework 5: Beginner to Guru, which covers Spring very well.

Its first few lessons are very important to learn spring framework because they explain to you how dependency injection provides improved testing, loose coupling, and help in writing clean code you always wanted.





Spring and Java HelloWorld Example

In this Spring tutorial, we will see one of the most simple examples of dependency Injection like  Hello Example. Message to Hello class is provided by the Spring framework using Dependency Injection.

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 a spring configuration file like spring-config.xml. All beans declared in the spring configuration file is created and managed by the 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 a 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 the "id" attribute of Hello bean declaration.

Btw, if you are a complete beginner on Spring framework and not familiar with essential Spring terminology like Beans, ApplicationContext etc, then I also suggest you to first go through Spring Fundamentals By Bryan Hansen on Pluralsight. A nice little course to understand the basics-of-basics of Spring framework

Spring Hello World Example in Java using XML Config




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

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 the following configuration files and Java classes.
  • Hello.java  - Hello Bean which prints given message provided 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 the constructor-arg tag.

If you are interested, you can also check Spring Master Class - Beginner to Expert course on Udemy for a couple of more examples on constructor injection and writing hello world using annotation in Spring 5.0.

Spring framework tutorial for beginners




Required Spring dependency JAR files

This Spring hello world example uses Spring 3.1.2.RELEASE.jar files but you can use the version you want like Spring 5.1 as well. Though, it's better to use Maven or Gradle for dependency injection because they will automatically download the right version of dependent JAR files for you. 
  • 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 the Main class as Java application from command line or Eclipse IDE. Btw, if you are interested in learning Spring 5 and Spring Boot 2 from scratch, in a guided, code-focused way, Learn Spring: The Certification Class Eugen is another awesome course to try out. 


Spring HelloWorld Java Class


import org.apache.log4j.Logger;

/*
 * Java class which accept the 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 the basics of Spring framework and dependency Injection design principle, writing Java program in Spring framework is really fun. 

In the next part of this tutorial, You will learn how to write Spring hello world using annotations and Java configuration, so stay tuned and till then enjoy the life, but if you can't wait here are some of the useful resources to learn Spring development using Annotations and Java Configuration.


Further Reading
Spring Framework 5: Beginner to Guru
Introduction to Spring MVC 4 By Bryan Hansen
Spring in Action 5th Edition


Other Spring Framework Articles you may like to explore this blog
  • 5 Free Spring and Spring Boot Courses to learn online (courses)
  • 23 Spring MVC Interview questions for 2 to 3 years experienced (list)
  • What is the use of DispatcherServlet in Spring MVC? (answer)
  • 20+ Spring and REST Interview Questions (questions)
  • 5 Online Courses to learn Spring Framework in depth (courses)
  • How to enable Spring security in Java application? (answer)
  • Does Spring certification help in Job and Career? (article)
  • Top 5 Spring Certification Mock Exams (list)
  • 5 Courses to learn Spring Cloud and Microservices (courses)
  • Difference between @Autowired and @Injection annotations in Spring? (answer)
  • 5 Spring and Hibernate online courses for Java developers (list)
  • 10 Spring Annotation Java Developers Should Know (annotations)
  • Top 5 Spring Boot Features for Java Developers (features)
  • 5 Courses to learn Spring Boot in Depth (Courses)

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