Core Spring Fundamentals: The Engine Under the Hood

9 min read

Welcome. When you first start building Java applications, you usually create objects exactly when you need them. You write new DatabaseConnection(), you write new UserService(), and you move on. But as your application grows, manually managing these objects becomes a tangled mess of code.

To build enterprise-grade applications with Spring Boot, you need to understand the fundamental engine that powers it. Spring is not magic; it is a highly structured system designed to solve specific problems related to object creation and management. Let us break down the core mechanics: Inversion of Control, Dependency Injection, Beans, and Scopes.


1. Inversion of Control (IoC): Giving Up Control for Good

The Problem

Imagine you are building a system for a restaurant. Your OrderService needs to save data, so it directly creates a DatabaseRepository.

java
public class OrderService {
    private DatabaseRepository repository = new DatabaseRepository();
    // ...
}

If you ever want to change the DatabaseRepository to a CloudRepository, or if the repository suddenly requires network credentials to be created, you have to modify the OrderService. Your classes are "tightly coupled." The OrderService is controlling the exact creation and lifecycle of its dependencies. If you do this across 500 classes, changing one core component requires hundreds of file modifications. You are essentially duct-taping your entire application together.

The Definition

Inversion of Control (IoC) is a design principle where the control flow of a program is inverted. Instead of the custom-written code calling reusable libraries and controlling object creation, the framework controls the program flow and provides the required objects to your custom code.

How IoC Solves the Problem

With IoC, your OrderService no longer creates its dependencies using the new keyword. It simply states, "I need a repository," and the surrounding system (the Spring container) creates and provides that repository. You give up the control of object creation to the framework.

Think of it like a modern automated warehouse. In a traditional warehouse (without IoC), a worker (your class) has to walk down the aisles, find the exact box they need, assemble the trolley, and bring it back. With an automated warehouse (IoC), the worker stands at a station and requests a specific type of item. The automated system finds it, brings it to them, and takes it away when they are done. The worker focuses only on packing the box, not on warehouse navigation.


2. Dependency Injection (DI): Wiring Things Together Conceptually

The Problem

If IoC is the abstract principle of giving up control, how do we actually implement it in code? How does the framework physically hand the DatabaseRepository to the OrderService without breaking Java's compilation rules?

The Definition

Dependency Injection (DI) is a specific design pattern used to implement IoC. It is the process where a framework supplies the dependencies of an object (usually via constructors or methods) rather than the object constructing them itself.

How DI Solves the Problem

DI allows Spring to "inject" pre-built objects into your classes.

In the industry, there are historically a few ways to inject dependencies in Spring, but Constructor Injection is the absolute industry standard.

The Industry Standard: Constructor Injection

Constructor injection forces the dependency to be provided when the object is instantiated. This ensures the object is never in a half-initialized state and makes testing incredibly easy.

java
// Industry Standard Practice
@Service
public class OrderService {
    
    // Marked as final because it should not change after creation
    private final OrderRepository orderRepository;

    // Spring automatically uses this constructor to inject the repository
    public OrderService(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }
    
    public void placeOrder() {
        orderRepository.save("New Order");
    }
}

Fun Fact: Back in the dark ages of early Spring, developers used massive XML files to manually wire every single dependency. A simple web app could have thousands of lines of XML. Thankfully, annotations saved us from that timeline.

What to Avoid: Field Injection

You might see tutorials using @Autowired directly on fields. Do not do this in modern applications.

java
// Bad Practice - Highly discouraged in modern Spring
@Service
public class OrderService {
    
    @Autowired // This hides the dependency and makes testing difficult
    private OrderRepository orderRepository; 
}

Field injection makes it impossible to instantiate the class without the Spring framework (e.g., in a unit test where you just want to pass a mock dependency), and it allows circular dependencies to go unnoticed until runtime. Stick to constructors.

(Pro tip: In modern Java industry codebases using Lombok, developers often use @RequiredArgsConstructor to auto-generate the constructor for all final fields, making the code even cleaner).


3. The Spring Container and Beans: @Component vs @Bean

The Problem

If Spring is going to inject objects for us, it needs to know what objects it is allowed to manage. It cannot just scan every single Java class in existence and load them into memory; it would crash instantly. It needs clear instructions on what belongs to the automated warehouse.

The Definition

  • The Spring Container (ApplicationContext): The core engine of Spring. It is the program that creates objects, wires them together, and manages their entire lifecycle.
  • Spring Beans: Any object that is instantiated, assembled, and managed by the Spring IoC container. If an object is not a Bean, Spring does not know about it.

The Solution: Registering Beans

There are two primary ways to tell Spring, "Hey, please manage this object for me." Understanding when to use which is a common stumbling block.

1. @Component (And its Stereotypes)

Use @Component when you are writing the class yourself. You just put the annotation on top of your class, and Spring's component scanner will find it automatically when the application starts.

Spring provides specialized versions of @Component (called stereotypes) to make your code more readable:

  • @Service: For business logic.
  • @Repository: For database operations.
  • @Controller / @RestController: For handling web requests.
java
// We wrote this class, so we use a stereotype annotation
@Service
public class PaymentProcessingService {
    // ...
}

2. @Bean (Inside @Configuration classes)

Use @Bean when you need to register a class from a third-party library that you cannot modify. Since you cannot open the source code of an external library (like a JSON parser or a web client) to paste @Component on top of it, you create a configuration class and write a method that returns the object.

java
@Configuration
public class AppConfig {

    // We didn't write RestTemplate, so we use @Bean to tell Spring to manage it
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

Rule of Thumb for Industry: If you own the code, annotate the class with @Service/@Component. If you are importing a library (like AWS SDK, external HTTP clients, specialized security encoders), configure it with @Bean.


4. Bean Scopes and Lifecycles: Singleton, Prototype, and Beyond

The Problem

When the Spring Container creates a Bean (like our OrderService), does it create a brand new one every single time another class asks for it? If 10,000 users hit our application at the same time, do we create 10,000 OrderService objects? That would destroy the server's memory.

The Definition

A Bean Scope determines the lifecycle and visibility of a bean instance. It dictates whether a single instance is shared or multiple instances are created.

The Solution: Spring Scopes

Spring solves memory management by using scopes. There are several, but only two are relevant for core logic, and one is king.

1. Singleton (The Default and Industry Standard)

By default, every Spring bean is a Singleton.
When the application starts, Spring creates exactly one instance of the bean. Every time a class asks for that bean, Spring hands over the exact same instance.

Because it is the same instance being shared across multiple web requests simultaneously, Beans must be stateless.

Imagine a coffee shop espresso machine (the Singleton Bean). There is only one machine. Multiple baristas (threads) use it. If the espresso machine stored the name of the customer inside its own internal memory, the barista making order #1 might accidentally get the name of customer #2. The machine should only contain the logic to make coffee, not the state of the specific order.

Never store user-specific data in a field of a Spring bean:

java
@Service
public class UserService {
    // DISASTER: This is a Singleton. This field is shared across ALL users!
    private String currentLoggedInUser; 

    // Correct: Pass state via method parameters
    public void processUser(String currentLoggedInUser) { ... }
}

2. Prototype (Rarely Used)

If you mark a bean as @Scope("prototype"), Spring will create a brand new instance every single time it is requested.
In enterprise Spring Boot, this is extremely rare. Almost 99% of your components will be Singletons. Prototypes are only used when an object holds temporary state that cannot be shared, but in modern Java, we usually just use the new keyword for simple stateful data objects (like a user payload) rather than making Spring manage them as Prototypes.

Briefly Under the Hood: The Lifecycle

When Spring starts, it goes through a strict order of operations for singletons:

  1. Instantiation: Spring looks at the classes, finds the constructors, and runs new.
  2. Dependency Injection: Spring injects required dependencies into those constructors.
  3. Post-Processing: (Optional) Spring runs any setup methods you annotated with @PostConstruct.
  4. Ready: The application starts serving traffic.
  5. Destruction: When the app shuts down, Spring safely closes connections and runs methods annotated with @PreDestroy.

By understanding that Spring wires everything before taking web requests, you can understand why Spring Boot apps take a few seconds to start up, but run lightning fast once they are ready.


Summary

  • IoC: The framework controls the flow and lifecycle of objects.
  • DI: The pattern used to give objects to classes that need them (always use Constructor Injection!).
  • Beans: Objects managed by Spring. Use @Component/@Service for your code, and @Bean for third-party code.
  • Scopes: Beans are Singletons by default. They are shared across the whole app, so keep them stateless!

References & Further Reading

Challenge

You are tasked with refactoring a small e-commerce application's service layer to adhere to modern Spring best practices. The existing code has several design flaws related to dependency injection, component scanning, and state management.

Your Tasks:

  1. Implement Constructor Injection: Modify the OrderService and ProductRepository classes to use constructor injection for their dependencies. The use of field injection (@Autowired on a field) is forbidden. Use Lombok's @RequiredArgsConstructor to generate the necessary constructors.
  2. Apply Stereotype Annotations: The current classes are using the generic @Component annotation. Replace it with the most semantically appropriate stereotype annotation for OrderService (business logic) and ProductRepository (data access).
  3. Configure a Third-Party Bean: The PaymentGateway class represents a client from an external library that you cannot modify. Create a new configuration class named AppConfig and declare the PaymentGateway as a Spring-managed @Bean within it.
  4. Enforce Singleton Statelessness: The SessionManager is a singleton bean that incorrectly stores mutable state (sessionId). Refactor it to be stateless. The session-specific data should be passed into its methods as a parameter, not stored in an instance field. Update the OrderService to accommodate this change when it interacts with the SessionManager.

Expected result

Your final code should consist of four correctly refactored or created classes/configurations.

  1. AppConfig.java

    • A new class annotated with @Configuration.
    • Contains a method annotated with @Bean that returns a new PaymentGateway() instance.
  2. SessionManager.java

    • The sessionId instance field must be removed.
    • The init() method annotated with @PostConstruct must be removed.
    • The getSessionId() method signature must be changed to public String getSessionId(String someSessionData) and it should process and return the data passed as a parameter.
    • It should retain its stereotype annotation (e.g., @Component or @Service).
  3. ProductRepository.java

    • Annotated with @Repository.
    • Annotated with @RequiredArgsConstructor.
    • The @Autowired annotation on the dataSource field must be removed.
    • The dataSource field must be declared as private final.
  4. OrderService.java

    • Annotated with @Service.
    • Annotated with @RequiredArgsConstructor.
    • All @Autowired field annotations must be removed.
    • The productRepository, paymentGateway, and sessionManager fields must all be declared as private final.
    • The call within the placeOrder method must be updated to pass the required session data to the refactored sessionManager.getSessionId() method. For example: sessionManager.getSessionId("some-session-token").
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.