Spring 5 Hello World Example


On this page, you will learn how to print Hello World or any other message on the console using Spring 5 framework.

This example will guide you step by step to develop the first program in Spring. Before staring all we need to download the Spring JAR file and configure it in Eclipse IDE.

Technologies Used

  1. Spring 5.0.2.RELEASE JAR
  2. Java 8
  3. Eclipse IDE

Dependencies Required

To developed core Spring application, you mainly required 5 JAR files as listed below.

  1. commons-logging-1.1.3.jar
  2. spring-beans-5.0.2.RELEASE.jar
  3. spring-context-5.0.2.RELEASE.jar
  4. spring-core-5.0.2.RELEASE.jar
  5. spring-expression-5.0.2.RELEASE.jar

You can also add the below dependency under the dependencies element if you are a Maven user.

pom.xml
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.0.2.RELEASE</version>
</dependency>

Project Structure

Find the project structure in Eclipse IDE.

Spring 5 Hello World Example

After setup, the Spring JAR in Eclipse IDE lets starts code step by step…

1- Spring Bean

Inside the beans package, create a simple class Greet that contains a method welcome().

Greet.java
package org.websparrow.beans;

public class Greet {

	public void welcome() {
		System.out.println("Welcome in Spring Framework.");
	}
}

2- Spring Bean Configuration

Configure the above Greet class in spring.xml file. Configuration file name can be anything. In my case, it was placed inside source folder src/main/resources.

spring.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" 
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
	<bean id="sayHello" class="org.websparrow.beans.Greet"></bean>
</beans>

3- Execution

Now the final step executes the code. To execute the code we need to read the configuration file spring.xml and call them by using bean id.

Hello.java
package org.websparrow.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.websparrow.beans.Greet;

public class Hello {
	public static void main(String[] args) {

		// read XML file
		@SuppressWarnings("resource")
		ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

		// create Greet object
		Greet gt = (Greet) context.getBean("sayHello");
		gt.welcome();

	}
}
Output:

When we execute the above code, it will print the following message in the console log.

Welcome in Spring Framework.

Download Source Code: spring-5-hello-world-example


Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.