Şuayb's BlogŞuayb's Blog
Home
Categories
Games
MediumAboutContact
Language
Theme
    1. Blog
    2. Programming
    3. Dependency Injection in Spring Boot

Dependency Injection in Spring Boot

PublishedDecember 18, 2024
UpdatedDecember 19, 2024
Reading time3 min read
JavaKotlinSpring BootDependency Injection
XLinkedInFacebook
Dependency Injection in Spring Boot

Loading likes...

Dependency Injection (DI) is a fundamental concept in Spring Boot that helps achieve loose coupling and increased testability. This guide demonstrates how to use DI in Spring Boot with practical examples in Java and Kotlin.


Last updatedDecember 19, 2024

Total viewsLoading hits...

Previous articleObject-Relational MappingNext articleAspect-Oriented Programming in Spring Boot
Şuayb Şimşek

Written by

Şuayb Şimşek

Backend-focused fullstack developer sharing practical notes on Spring Boot, security, microservices, and cloud-native architecture.

Expertise

  • Spring Boot
  • Go
  • Microservices
  • Next.js
  • Cloud Native

Connect

GitHubLinkedInMedium

Related posts

Spring Boot Configuration Properties
Programming

Spring Boot Configuration Properties

Learn how to use @ConfigurationProperties for type-safe configuration, validate settings with @Validated, and manage environment-specific values with profile-specific application-{profile}.yml files.

February 4, 20263 min read
JavaKotlinSpring BootConfiguration
Spring Boot GraphQL JWE Authentication
Programming

Spring Boot GraphQL JWE Authentication

Learn how to secure your Spring Boot GraphQL APIs with stateless encrypted JWTs (JWE) while persisting user identities and roles in a JPA-backed database.

May 17, 20256 min read
JavaKotlinSpring BootSecurityJWTJWEGraphQL
Spring Boot JWE Authentication with JPA
Programming

Spring Boot JWE Authentication with JPA

Learn how to use stateless encrypted JWTs (JWE) to secure your Spring Boot APIs while persisting user identities and roles in a JPA-backed database.

May 11, 20254 min read
JavaKotlinSpring BootSecurityJWTJWEJPA

About

Articles on Spring Boot, microservices, security, and more.

ContactStart here

Latest posts

  • Captain Tsubasa 2: World Fighters
  • Captain Tsubasa: Rise of New Champions
  • Spring Boot Configuration Properties
  • Spring Boot GraphQL JWE Authentication
  • Spring Boot JWE Authentication with JPA

Top topics

JavaKotlinSpring BootJWEJWTMicroservice

Subscribe

Get practical backend + fullstack notes when new articles are published.

Social

© 2024-2026 Şuayb's Blog. All rights reserved.

🌟 Why Use Dependency Injection?

Dependency Injection allows developers to manage and inject dependencies into classes without manually instantiating them. This leads to:

  • Better code modularity
  • Simplified testing
  • Easier maintenance

📋 Prerequisites

📋 Ensure you have the following:

  • ☕ Java Development Kit (JDK) 17+
  • 📦 Maven or Gradle installed
  • 🔤 A Java IDE (e.g., IntelliJ IDEA, Eclipse)

🛠️ Step 1: Add Dependencies

Include the necessary Spring Boot dependencies:

Maven:

XMLpom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
</dependency>

Gradle:

GROOVYbuild.gradle
implementation 'org.springframework.boot:spring-boot-starter'

🛠️ Step 2: Create a Service

Define a simple service to demonstrate DI.


🛠️ Step 3: Inject Dependencies

Use annotations to inject the service into other components.


▶️ Running the Application

Run the application using the following commands:

Spring Boot (Java/Kotlin): Run the application with either stack to confirm the baseline setup is working before deeper tests.

BASH
./mvnw spring-boot:run

Access the API at http://localhost:8080/api/users.


🧪 Test the API

You can test the API using the following cURL commands:

Fetch all users

Use this request to verify the list endpoint and validate the default response shape.

BASH
curl -X GET http://localhost:8080/api/users

Fetch a user by ID

Use this request to validate path-variable handling and single-resource retrieval behavior.

BASH
curl -X GET http://localhost:8080/api/users/1

🏁 Conclusion

You now have a practical Dependency Injection in Spring Boot implementation with a clear, production-friendly Spring Boot structure. As a next step, adapt configuration and tests to your own domain, then validate behavior under realistic traffic and failure scenarios.

Service

JAVAUserService.java
package com.example.demo.service;

import org.springframework.stereotype.Service;

@Service
public class UserService {

    public String getUserById(String id) {
        return "User with ID: " + id;
    }

    public String getAllUsers() {
        return "Fetching all users.";
    }
}

Service

KOTLINUserService.kt
package com.example.demo.service

import org.springframework.stereotype.Service

@Service
class UserService {

    fun getUserById(id: String): String {
        return "User with ID: $id"
    }

    fun getAllUsers(): String {
        return "Fetching all users."
    }
}

Controller

JAVAUserController.java
package com.example.demo.controller;

import com.example.demo.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @GetMapping("/{id}")
    public String getUserById(@PathVariable String id) {
        return userService.getUserById(id);
    }

    @GetMapping
    public String getAllUsers() {
        return userService.getAllUsers();
    }
}

Controller

KOTLINUserController.kt
package com.example.demo.controller

import com.example.demo.service.UserService
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/api/users")
class UserController(
    private val userService: UserService
) {

    @GetMapping("/{id}")
    fun getUserById(@PathVariable id: String): String = userService.getUserById(id)

    @GetMapping
    fun getAllUsers(): String = userService.getAllUsers()
}