Building Your First REST API with Spring Boot in Under 10 Minutes

Creating a simple REST API using Spring Boot can be a smooth process, and it is entirely possible to get it done in under 10 minutes. Here’s a step-by-step guide to building your first REST API:

1. Setup Your Spring Boot Project

  1. Go to Spring Initializr.
  2. Configure the project:
    • Project: Maven.
    • Language: Java.
    • Spring Boot Version: Choose the latest stable version.
    • Dependencies: Add Spring Web (this adds support for creating a REST API).
  3. Click to download the project as a .zip file. Generate

  4. Extract the file, then open it in your favorite IDE like IntelliJ IDEA.

2. Create a REST Controller

A REST controller handles HTTP requests and maps them to methods. You will use the @RestController annotation to create a REST API in Spring Boot.
Create a file under src/main/java/com/example/demo/ named : HelloWorldController.java

package com.example.demo;

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

@RestController
@RequestMapping("/api")
public class HelloWorldController {

    @GetMapping("/hello")
    public String helloWorld() {
        return "Hello, World!";
    }
}
  • Annotations Explained:
    • @RestController: Combines @Controller and @ResponseBody, enabling REST-specific behavior.
    • @RequestMapping: Specifies the base path for this controller (e.g., /api).
    • @GetMapping: Handles HTTP GET requests for the /hello sub-endpoint.

3. Run Your Application

  1. Run your application by navigating to the DemoApplication class and executing the method (Run button in IntelliJ). main
  2. By default, your application will start on port 8080.

4. Test Your REST API

Hello, World!

5. (Optional) Add Another Endpoint Returning JSON

If you want to return a JSON response, create a new endpoint:

@GetMapping("/greet")
public Greeting greetUser() {
    return new Greeting("Welcome to Spring Boot!");
}

Create a new class Greeting.java under the same package:

package com.example.demo;

public class Greeting {

    private String message;

    public Greeting(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
{
    "message": "Welcome to Spring Boot!"
}

6. Complete!

Congratulations, you’ve successfully created your first REST API with Spring Boot!

How do I inject environment-specific values using Spring Profiles?

Spring Profiles provide a flexible way to load environment-specific configurations in a Spring-based application. Here’s a step-by-step guide on how to use them:

Steps to Inject Environment-Specific Values Using Spring Profiles

  1. Define Profile-Specific Properties Files
    Create separate property files for different environments (e.g., development, testing, production). Make sure to name them with a clear convention.

    Examples:

    • application-dev.properties (for development)
    • application-prod.properties (for production)
    • application-test.properties (for testing)

    In these files, define environment-specific values.
    Example (application-dev.properties):

    app.name=MyApp (Dev Environment)
    app.url=http://localhost:8080
    

    Example (application-prod.properties):

    app.name=MyApp (Production)
    app.url=https://myapp.com
    
  2. Activate the Profile
    Use one of the following methods to specify which profile is active:

    • In application.properties or application.yml: Add the spring.profiles.active property.
    spring.profiles.active=dev
    
    • As a Command-Line Argument:
      You can pass the profile during application startup:
    java -jar myapp.jar --spring.profiles.active=prod
    
    • As an Environment Variable:
      Set the SPRING_PROFILES_ACTIVE environment variable:
    export SPRING_PROFILES_ACTIVE=prod
    
  3. Use the @Profile Annotation in Beans (Optional)
    Annotate components or configurations that should only load in specific profiles using the @Profile annotation.

    Example:

    @Component
    @Profile("dev")
    public class DevDatabaseInitializer { 
        public DevDatabaseInitializer() {
           System.out.println("Initializing Development Database...");
        }
    }
    

    The above bean will only be loaded when the “dev” profile is active.

  4. Access Values from Properties Files
    Use @Value or the @ConfigurationProperties annotation to inject values into your code.

    Example:

    @Component
    public class AppConfig {
        @Value("${app.name}")
        private String appName;
    
        @Value("${app.url}")
        private String appUrl;
    
        public void printConfig() {
           System.out.println("App Name: " + appName);
           System.out.println("App URL: " + appUrl);
        }
    }
    
  5. (Optional) Use application.yml for Profile-Specific Configuration
    Instead of multiple property files, you can use a single application.yml with profile-specific sections:

    spring:
      profiles:
        active: dev
    
    ---
    spring:
      profiles: dev
      app:
        name: MyApp (Dev Environment)
        url: http://localhost:8080
    
    ---
    spring:
      profiles: prod
      app:
        name: MyApp (Production)
        url: https://myapp.com
    

Using Spring Profiles allows you to maintain clean and environment-specific configurations, reducing the chance of errors and simplifying the deployment process.

How Dependency Injection Works in Spring Boot Using @Autowired

Dependency Injection (DI) is a fundamental concept in Spring Boot that facilitates the management of dependencies between various components in your application. Spring Boot primarily uses the @Autowired annotation to enable automatic wiring of beans. Below, I’ll explain how Dependency Injection works using @Autowired in Spring Boot, step by step.

What is Dependency Injection?

Instead of creating dependencies manually within components, Spring’s IoC (Inversion of Control) container injects dependencies into an object automatically. This reduces tight coupling and makes code more reusable and flexible.

How Does @Autowired Work?

@Autowired is used to mark a dependency that Spring should handle automatically. It tells Spring, “Find the appropriate bean in the IoC container and inject it here.”

Here’s how it works:

  1. Mark the class as a Spring Bean using @Component, @Service, @Repository, or by defining it explicitly via @Bean in a configuration class.
  2. Use the @Autowired Annotation to inject a required dependency into a field, constructor, or setter method.

Approaches to Using @Autowired

1. Field Injection

This is the simplest form of dependency injection where the field is annotated with @Autowired.

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class CarService {

    @Autowired
    private Engine engine;

    public void startCar() {
        engine.start();
    }
}
@Component
public class Engine {
    public void start() {
        System.out.println("Engine started!");
    }
}
  • Pros: Quick and readable.
  • Cons: Field injection is less testable and not recommended for complex applications because the dependency is hard to mock in unit tests.

2. Constructor Injection (Recommended)

Here, dependencies are injected via the constructor. This is the most preferred approach as it promotes immutability and easy testing.

import org.springframework.stereotype.Component;

@Component
public class CarService {

    private final Engine engine;

    @Autowired // Optional in Spring Boot since 4.3+
    public CarService(Engine engine) {
        this.engine = engine;
    }

    public void startCar() {
        engine.start();
    }
}
@Component
public class Engine {
    public void start() {
        System.out.println("Engine started!");
    }
}
  • Pros: Cleaner, better for unit testing, adheres to immutability principles.
  • Cons: Requires explicit constructors, but modern tools (e.g., Lombok) simplify this.

3. Setter Injection

Dependencies are injected via setter methods. This is helpful when a bean property is optional and not required during object creation.

import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
public class CarService {

    private Engine engine;

    @Autowired
    public void setEngine(Engine engine) {
        this.engine = engine;
    }

    public void startCar() {
        engine.start();
    }
}
@Component
public class Engine {
    public void start() {
        System.out.println("Engine started!");
    }
}
  • Pros: Useful when you want to inject optional dependencies.
  • Cons: Makes the class mutable and harder to test.

Behind the Scenes

  1. Bean Discovery: The Spring IoC container detects beans annotated with @Component, @Service, @Repository, @Controller, or those defined explicitly in configuration classes.
  2. Dependency Resolution: When @Autowired is detected on a field, constructor, or setter, Spring scans its ApplicationContext to find a matching bean (by type).
  3. Injection: The resolved bean (dependency) is injected into the target where @Autowired is present.

Handling Ambiguity

If multiple beans of the same type are defined, Spring would throw a NoUniqueBeanDefinitionException. You can resolve this by:

  • Using @Qualifier:
@Autowired
@Qualifier("specificEngine")
private Engine engine;
  • Marking a bean as a primary candidate:
@Primary
@Component
public class Engine { ... }

Example: A Working Spring Boot Application

Here’s a complete example of how @Autowired can be used in a Spring Boot application.

Application Entry Point

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

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

Service & Dependency

import org.springframework.stereotype.Service;

@Service
public class GreetingService {

    public String getGreeting() {
        return "Hello, Dependency Injection!";
    }
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private final GreetingService greetingService;

    public GreetingController(GreetingService greetingService) {
        this.greetingService = greetingService;
    }

    @GetMapping("/greet")
    public String greet() {
        return greetingService.getGreeting();
    }
}

Run the application, and visiting http://localhost:8080/greet will give you the message:
Hello, Dependency Injection!

Best Practices

  1. Use Constructor Injection for mandatory dependencies.
  2. Avoid Field Injection, except for small applications or testing purposes.
  3. Annotate beans properly using stereotypes like @Service, @Component, etc.
  4. For optional beans, use @Autowired(required = false) or setter injection.
  5. Handle bean ambiguity with @Qualifier or @Primary.

How do I use lifecycle callbacks like @PostConstruct and @PreDestroy in Spring beans?

In Spring, the lifecycle of a bean can be managed, and you can hook into these lifecycle phases using annotations like @PostConstruct and @PreDestroy.

  1. @PostConstruct:
    • This annotation is part of Jakarta annotations (not proprietary to Spring).
    • It is used to execute initialization logic after the bean’s properties have been set (i.e., after dependency injection is complete).
  2. @PreDestroy:
    • This annotation is also part of Jakarta annotations.
    • It is used to define a clean-up method that Spring calls before the bean is destroyed, typically during application shutdown.

To use these annotations in a Spring-managed bean:

Example with a Spring Bean:

package org.kodejava.spring;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    public MyBean() {
        System.out.println("MyBean constructor called");
    }

    @PostConstruct
    public void init() {
        System.out.println("MyBean @PostConstruct called: Initialization logic here");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("MyBean @PreDestroy called: Cleanup logic here");
    }
}

Explanation:

  1. Constructor: When the bean is instantiated by Spring, the constructor is called.
  2. @PostConstruct (Initialization logic): Once the bean is instantiated and its dependencies are injected, this annotated method is invoked automatically.
  3. @PreDestroy (Cleanup logic): Before the bean is destroyed (typically when the application context is being closed), this annotated method is invoked automatically.

Notes:

  • Newer versions of Spring Boot automatically include this dependency.
  • If you’re working on Spring Boot, your application supports these lifecycle callbacks out of the box.

Alternative for Lifecycle Management:

You can also achieve similar functionality using Spring’s InitializingBean and DisposableBean interfaces or by explicitly configuring init and destroy methods in the bean definitions.

package org.kodejava.spring;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class MyBean implements InitializingBean, DisposableBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("MyBean initializing using InitializingBean");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("MyBean destroying using DisposableBean");
    }
}

However, using @PostConstruct and @PreDestroy is generally preferred because they are more concise and not tightly coupled to Spring APIs.


Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>6.2.6</version>
    </dependency>
    <dependency>
        <groupId>jakarta.annotation</groupId>
        <artifactId>jakarta.annotation-api</artifactId>
        <version>3.0.0</version>
    </dependency>
</dependencies>    

Maven Central Maven Central

Understanding @SpringBootApplication: The Heart of a Spring Boot App

The @SpringBootApplication annotation is a cornerstone of any Spring Boot application. It simplifies the configuration process and integrates core functionalities of Spring Boot in a single, convenient annotation. Here’s a comprehensive explanation to help you understand its importance and functionality:


What is @SpringBootApplication?

@SpringBootApplication is a composite annotation that combines three common Spring annotations to reduce configuration complexity. These annotations are:

  1. @SpringBootConfiguration
    • Denotes that this class is a configuration class.
    • Equivalent to Spring’s @Configuration annotation.
    • Allows the application to define @Bean definitions and Spring container settings.
  2. @EnableAutoConfiguration
    • Enables Spring Boot’s auto-configuration mechanism.
    • Automatically configures the Spring application based on the dependencies declared in the project.
    • For instance, if spring-boot-starter-web is in your dependencies, it will configure web-related beans like DispatcherServlet, ViewResolvers, etc.
  3. @ComponentScan
    • Scans the package where the annotated class resides and its sub-packages for Spring components (e.g., @Component, @Service, @Repository, @Controller, etc.).
    • This ensures that all required Spring-managed components are registered in the application context.

By combining these three annotations, @SpringBootApplication provides a streamlined way to configure and bootstrap Spring Boot applications.


Advantages of @SpringBootApplication

  1. Reduced Boilerplate Code
    Developers don’t need to explicitly annotate the main application class with @Configuration, @EnableAutoConfiguration, and @ComponentScan. The single annotation @SpringBootApplication takes care of it all.

  2. Auto-Configuration
    The @EnableAutoConfiguration part ensures that Spring Boot configures most components for you based on the classpath dependencies.

  3. Ease of Use
    Simplifies managing configurations and makes the application easier to understand and develop.


Where Should You Place @SpringBootApplication?

The @SpringBootApplication annotation is typically placed on the main class of the application, which is also the entry point for the main method. By convention, this main class should be located in the base package of the application. This ensures that the @ComponentScan directive will pick up all components, services, and controllers in sub-packages.

For example:

package org.kodejava.springboot.demo;

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

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

If your application’s main class is not located in the base package, you’ll need to manually configure the package path using the @ComponentScan annotation.


Customization Options of @SpringBootApplication

In some scenarios, you might want to override the default behavior of @SpringBootApplication by customizing its inner behavior:

  • Excluding Certain Auto-Configurations
    If you want to disable specific parts of Spring Boot’s auto-configuration:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  • Setting Scanning Packages
    You can explicitly define scanning behavior using the @ComponentScan annotation:
@SpringBootApplication
@ComponentScan(basePackages = {"org.kodejava.springboot.demo.service", "org.kodejava.springboot.demo.dao"})
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Keynotes

  1. Auto-Configuration Priority:
    • Auto-configuration mechanisms can be fine-tuned or overridden through application.properties or custom configuration classes.
  2. SpringApplication.run:
    • This method in the main method initializes the Spring application context and launches it.
  3. Custom Beans:
    • @SpringBootApplication does not prevent you from defining custom Beans or configurations if needed. You can still use annotations like @Bean and @Configuration alongside it.

Conclusion

@SpringBootApplication eliminates a lot of boilerplate code, making Spring Boot applications easier to configure and start. It combines the functionality of several essential Spring annotations into one. For most Spring Boot applications, simply annotating the main class with @SpringBootApplication is sufficient to bootstrap the application with sensible defaults, making it the “heart” of any Spring Boot app!


Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>3.4.4</version>
    </dependency>
</dependencies>

Maven Central