Loading...

Chapter 6: Spring - Hello World Example

Introduction

Now that we’ve set up our environment, it’s time to create a simple Spring application. In this chapter, we will create a basic Hello World application using Spring Framework to help you understand how to structure a Spring project, define beans, and leverage the Inversion of Control (IoC) container.

By the end of this chapter, you’ll know how to:

  • Configure Spring Beans
  • Use dependency injection
  • Run a Spring application

Let’s get started!


Step 1: Create a New Spring Project

If you are using Spring Initializr to generate the project, follow these steps:

  1. Visit Spring Initializr.
  2. Select Maven or Gradle as the build tool.
  3. Choose Java as the programming language.
  4. Select Spring Web dependency.
  5. Click Generate to download the project.

After the download, unzip the project and open it in your favorite IDE.

If you are setting up manually, follow the steps from the previous chapter to create a Maven or Gradle project and include dependencies like spring-context in the pom.xml or build.gradle file.


Step 2: Create the Bean

First, let’s create a simple bean that will hold the logic for displaying the Hello World message.

  1. Create a package com.example.springapplication in your project.
  2. Inside the package, create a class HelloWorldService.java.
package com.example.springapplication;

public class HelloWorldService {
    
    public void sayHello() {
        System.out.println("Hello, World!");
    }
}

In this class, we have a simple method sayHello() that prints the string “Hello, World!” to the console.


Step 3: Configure the Spring Bean

Now, we need to tell Spring how to manage the HelloWorldService class by configuring it as a Spring bean.

  1. Create a configuration class called AppConfig.java in the same package com.example.springapplication:
package com.example.springapplication;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {
    
    @Bean
    public HelloWorldService helloWorldService() {
        return new HelloWorldService();
    }
}

In this configuration class, we use the @Configuration annotation to indicate that this class contains Spring configuration. The @Bean annotation tells Spring to create a bean of type HelloWorldService that can be injected into other components.


Step 4: Create the Main Application

Next, let’s create a MainApp.java file to run the Spring application and invoke the HelloWorldService.

  1. In the same package com.example.springapplication, create the MainApp.java class:
package com.example.springapplication;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {
    public static void main(String[] args) {
        // Initialize Spring IoC container
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        // Retrieve the bean from the container
        HelloWorldService helloWorldService = context.getBean(HelloWorldService.class);

        // Call the method on the bean
        helloWorldService.sayHello();

        // Close the context
        context.close();
    }
}

Here’s a breakdown of what the code does:

  • We create an instance of the Spring IoC container using AnnotationConfigApplicationContext. This container will scan the AppConfig.class configuration and initialize the beans defined there.
  • We retrieve the HelloWorldService bean from the container using context.getBean(HelloWorldService.class).
  • We call the sayHello() method on the HelloWorldService bean, which prints “Hello, World!” to the console.
  • Finally, we close the Spring context using context.close() to release resources.

Step 5: Run the Application

To run the application, simply execute the MainApp.java class. If you’re using Maven, you can also run the application using the following command:

mvn clean install
mvn exec:java

When you run the program, you should see the output:

Hello, World!

This confirms that the Spring IoC container is managing the HelloWorldService bean and has successfully injected it into the application.


Step 6: Understanding the Flow

  1. Bean Configuration: In the AppConfig class, we configured the HelloWorldService as a Spring bean using the @Bean annotation.
  2. IoC Container: When the application runs, Spring’s IoC container initializes and manages the beans defined in the configuration class (AppConfig).
  3. Dependency Injection: Although this example doesn’t show injection between beans, Spring’s dependency injection is at work behind the scenes.
  4. Application Context: The AnnotationConfigApplicationContext is used to load the configuration class and manage the Spring beans.

Conclusion

In this chapter, we created a simple Hello World application using Spring Framework. We:

  • Defined a service bean (HelloWorldService).
  • Configured the bean in a Java-based Spring configuration (AppConfig).
  • Retrieved and used the bean from the Spring IoC container in our main application (MainApp).

This is just the beginning. In the next chapters, we will explore more advanced Spring concepts, such as IoC Containers, Bean Scopes, and Dependency Injection.