Spring Beans

Introduction

Welcome to this lesson! So far, you have explored the foundational structure of a Spring Boot project. In this lesson, you'll delve into a crucial aspect of Spring Boot — Spring Beans. You'll learn how to create, manage, and utilize Spring Beans. Together, we'll understand dependencies, manual dependency management, Inversion of Control (IoC), and Dependency Injection (DI). We'll explore annotations like @Component and @Bean and see how they simplify dependency management using Spring Context. By the end of this lesson, you'll be equipped to leverage Spring's capabilities for effective bean management.

What is a Dependency?

Before diving into Spring Beans, let's clarify what a dependency is. Imagine you're building an application to prepare a sandwich. You can create a few classes like Bread, Lettuce, Tomato, and Cheese. Obviously, you'll also need a Grill class. Lastly, you'll need a skilled person to put all these ingredients together — the sandwich maker. The sandwich maker requires all the ingredients and a grill to prepare the sandwich, so all these objects are dependencies of the sandwich maker.

Understanding the Problem

Now, let's understand the complication of manually managing object dependencies. Imagine you need to grill a sandwich and you manually create all the ingredients and the grill. Here’s a simplified code snippet to demonstrate this:

class Bread
class Lettuce
class Tomato
class Cheese
class Sandwich
class Grill

class SandwichMaker(
    private val grill: Grill,
    private val bread: Bread,
    private val lettuce: Lettuce,
    private val tomato: Tomato,
    private val cheese: Cheese
) {
    fun prepareSandwich(): Sandwich {
        println("Sandwich is ready!")
        return Sandwich()
    }
}

fun main() {
    val grill = Grill()
    val bread = Bread()
    val lettuce = Lettuce()
    val tomato = Tomato()
    val cheese = Cheese()
    val sandwichMaker = SandwichMaker(grill, bread, lettuce, tomato, cheese)
    sandwichMaker.prepareSandwich()
}

In this example, you manually handle all dependencies. While it looks simple, you need to ensure that you create all objects without dependencies first (bread, lettuce, tomato, and cheese) before constructing the more complex sandwichMaker object that requires these dependencies. Now, imagine you're working on an application for car manufacturing, where you try to assemble a car with thousands of components. As the number of dependencies grows, managing them manually becomes increasingly cumbersome.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal