Spring Boot @SpringBootApplication Example

1. Introduction

The @SpringBootApplication annotation is a convenience annotation in Spring Boot that encapsulates @Configuration, @EnableAutoConfiguration, and @ComponentScan annotations. It provides a way to quickly and easily set up a new Spring application with sensible defaults.

Key Points:

1. @SpringBootApplication is the starting point for a Spring Boot application.

2. It triggers auto-configuration, component scanning, and configuration properties support.

3. It simplifies the initial bootstrapping of a Spring application.

2. Implementation Steps

1. Create a new Spring Boot project using Spring Initializr or your preferred development setup.

2. Define the main application class with the @SpringBootApplication annotation.

3. Create controller, service, and repository classes to demonstrate component scanning.

4. Run the main application class as a Java application.

3. Implementation Example

Here is the complete code that demonstrates the usage of @SpringBootApplication annotation:
// Step 2: Define the main application class with @SpringBootApplication
@SpringBootApplication
public class MyApp {

    public static void main(String[] args) {
        // Step 4: Run the Spring Boot application
        SpringApplication.run(MyApp.class, args);
    }
}

// Step 3: Create a simple REST controller
@RestController
class HelloController {

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

Run:

mvn spring-boot:run

Output:

When the application is running, navigate to http://localhost:8080 in a web browser and you should see:
Hello, World!

Explanation:

1. @SpringBootApplication marks the MyApp class as the configuration class and bootstraps the Spring Boot application.

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

3. HelloController is a REST controller that is automatically detected by component scanning because it is in the same or a sub-package of MyApp.

4. The sayHello method is mapped to the root URL ("/") and returns a simple "Hello, World!" response.

5. The output "Hello, World!" is displayed when a GET request is made to the root URL, indicating that the application is running and the controller is responding as expected.

6. The @SpringBootApplication annotation enables auto-configuration, which sets up the default configuration for a web application, including the embedded Tomcat server on port 8080.


Comments