Skip to main content

Spring Hello World

Introduction

Welcome to the world of Spring Framework! If you're new to Spring, you're about to discover one of the most powerful and widely-used Java frameworks in the industry. In this tutorial, we'll create a simple "Hello World" application using Spring to help you understand the basic concepts and structure of a Spring project.

Spring Framework is a comprehensive programming and configuration model for modern Java-based enterprise applications. It offers a simpler alternative to the complexity of building enterprise-level applications with Java, by providing ready-made components and a well-structured architecture.

Prerequisites

Before we start, make sure you have:

  1. Java Development Kit (JDK) 8 or higher installed
  2. A build tool like Maven or Gradle
  3. An Integrated Development Environment (IDE) such as IntelliJ IDEA, Eclipse, or Visual Studio Code

Creating a Simple Spring Hello World Application

Let's build our first Spring application step by step.

Step 1: Set Up a New Project

We'll use Spring Initializr to create our project structure. You can either:

  • Visit Spring Initializr in your browser
  • Use your IDE's Spring Initializr integration

For this tutorial, let's configure our project as follows:

  • Project: Maven
  • Language: Java
  • Spring Boot: Latest stable version
  • Group: com.example
  • Artifact: spring-hello-world
  • Dependencies: Spring Web

Click "Generate" to download a ZIP file containing your project.

Step 2: Explore the Project Structure

After extracting the ZIP, you'll see a structure like this:

spring-hello-world/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── springhelloworld/
│ │ │ └── SpringHelloWorldApplication.java
│ │ └── resources/
│ │ └── application.properties
│ └── test/
│ └── java/
│ └── com/
│ └── example/
│ └── springhelloworld/
│ └── SpringHelloWorldApplicationTests.java
├── pom.xml
└── ...

The pom.xml file contains your project dependencies. Spring Boot has automatically configured everything you need to get started.

Step 3: Understand the Main Application Class

Let's look at the automatically generated main class:

java
package com.example.springhelloworld;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringHelloWorldApplication {

public static void main(String[] args) {
SpringApplication.run(SpringHelloWorldApplication.class, args);
}
}

The @SpringBootApplication annotation is a convenience annotation that adds:

  • @Configuration: Tags the class as a source of bean definitions
  • @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings
  • @ComponentScan: Tells Spring to look for components in the current package

The main method uses SpringApplication.run() to launch the application.

Step 4: Create a Simple Controller

Now let's add a controller to handle web requests. Create a new file named HelloController.java in the same package:

java
package com.example.springhelloworld;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring World!";
}
}

Let's understand each part:

  • @RestController: Combines @Controller and @ResponseBody, which means this class will handle HTTP requests and responses will be automatically converted to the appropriate format (in this case, text)
  • @GetMapping("/hello"): Routes HTTP GET requests to the "/hello" path to the sayHello() method
  • The sayHello() method returns a simple string that will be displayed in the browser

Step 5: Run the Application

Now let's run our application:

  1. In your IDE, right-click on SpringHelloWorldApplication.java and select "Run"
  2. Alternatively, navigate to your project directory in a terminal and run:
    ./mvnw spring-boot:run  # For Maven
    or
    ./gradlew bootRun  # For Gradle

When the application starts, you should see output similar to this:

  .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.x)

2023-07-10 10:15:42.123 INFO 12345 --- [main] c.e.s.SpringHelloWorldApplication : Starting SpringHelloWorldApplication...
...
2023-07-10 10:15:45.678 INFO 12345 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http)
...
2023-07-10 10:15:45.900 INFO 12345 --- [main] c.e.s.SpringHelloWorldApplication : Started SpringHelloWorldApplication in 3.751 seconds

Step 6: Test the Endpoint

Open a web browser and navigate to:

http://localhost:8080/hello

You should see the text: "Hello, Spring World!"

Congratulations! You've created your first Spring application.

Understanding What's Happening Behind the Scenes

Let's break down what Spring is doing:

  1. The @SpringBootApplication annotation sets up Spring's auto-configuration
  2. Spring Boot automatically configures an embedded web server (Tomcat by default)
  3. Your HelloController class is detected during component scanning
  4. Spring creates a REST endpoint at /hello that returns your message
  5. When you access the URL, Spring routes the request to your controller method

Enhancing Our Hello World Application

Let's make our application a bit more dynamic by adding a parameter:

java
package com.example.springhelloworld;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@GetMapping("/hello")
public String sayHello(@RequestParam(value = "name", defaultValue = "Spring") String name) {
return String.format("Hello, %s World!", name);
}
}

Now restart your application and try:

http://localhost:8080/hello?name=Java

The output should be: "Hello, Java World!"

Real-World Application Context

In real-world applications, Spring's capabilities go far beyond this simple example:

  1. Enterprise Applications: Spring provides modules for data access, security, cloud computing, and more
  2. Microservices: Spring Boot is ideal for building microservices that can run independently
  3. Web Applications: Spring MVC offers a powerful framework for building web applications
  4. RESTful APIs: As we've seen, Spring makes it easy to create RESTful services

For instance, a real e-commerce application might use:

  • Spring Data JPA for database operations
  • Spring Security for authentication
  • Spring Cloud for microservice communication
  • Thymeleaf for server-side rendering

Summary

In this tutorial, we:

  1. Created a new Spring Boot application
  2. Added a simple REST controller
  3. Ran the application and tested our endpoint
  4. Enhanced the application to accept parameters

You've taken your first steps into the Spring ecosystem! This simple "Hello World" application demonstrates Spring's approach to building Java applications—providing powerful features through minimal, concise code.

Next Steps and Resources

To continue your Spring journey:

  1. Explore Spring Beans: Learn how Spring manages objects using dependency injection
  2. Database Integration: Connect your Spring application to a database using Spring Data
  3. Spring MVC: Build more complex web applications with Spring's MVC framework

Additional Resources

Exercise

Try these challenges to reinforce your learning:

  1. Add another endpoint that returns the current date and time
  2. Modify the hello endpoint to accept a language parameter and respond with greetings in different languages
  3. Create a simple HTML form that sends a name to your hello endpoint and displays the response

Happy coding with Spring!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)