Learn Spring · 2/15

Spring Core Fundamentals: The Engine of Spring

8 min read

Welcome to the heart of Spring. If you have ever looked at a massive enterprise Java project and wondered how thousands of classes communicate without turning into a tangled web of new keywords, you are in the right place.

In this guide, we are going deep into Spring Core. We will progress step-by-step, starting from the basic container that holds your application together, down to the exact lifespan of the objects living inside it.

Let's get started.


🛠️ The Boilerplate: Getting Started

Before we learn the concepts, you need a place to write code. In modern industry practice, nobody sets up Spring Core from scratch using XML files (unless they are maintaining a project from 2008). We use Spring Boot to bootstrap Spring Core.

  1. Go to Spring Initializr.
  2. Select the following to get the latest industry-standard setup:
    • Project: Maven or Gradle
    • Language: Java
    • Spring Boot: 3.2.x or 3.3.x (Latest stable)
    • Java: 17 or 21
  3. Click Generate, extract the zip, and open it in your favorite IDE (IntelliJ IDEA is highly recommended).

Now, let's learn how the engine actually works.


1. The ApplicationContext: Spring's Beating Heart 🫀

Definition:
The ApplicationContext is an interface representing the Spring IoC (Inversion of Control) container. It is responsible for instantiating, configuring, assembling, and managing the lifecycle of the objects in your application.

The Problem:
In standard Java, if Class A needs Class B to work, Class A usually creates it directly using the new keyword.

java
public class PaymentProcessor {
    private NotificationService notificationService = new NotificationService();
    private DatabaseConnection dbConnection = new DatabaseConnection();
}

This tightly couples your classes. If DatabaseConnection suddenly requires a URL parameter in its constructor, you have to find every single place in your massive codebase where you typed new DatabaseConnection() and fix it. You also waste memory by creating duplicate instances of standard utility classes.

The Solution:
Spring introduces Inversion of Control (IoC). Instead of you controlling the creation of objects, you hand that control over to Spring. The ApplicationContext acts as a giant registry. At startup, it creates all your objects, figures out who needs what, and hands them out.

Real-life Scenario:
Imagine a large restaurant. If a waiter needs a salad, they do not go to the farm, grow tomatoes, chop them, and build the salad themselves (using the new keyword). They just ask the Kitchen (the ApplicationContext) for a salad. The Kitchen already knows how to make it, has all the ingredients ready, and hands the finished product to the waiter.

Under the hood, when your Spring Boot app starts, it creates this ApplicationContext automatically. You rarely interact with it directly; it just sits in the background, quietly managing your application.


2. Creating and Managing Beans: @Component, @Service, and @Repository 🫘

Definition:
A Bean is simply an object that is instantiated, assembled, and managed by a Spring IoC container.

The Problem:
Spring's ApplicationContext is powerful, but it cannot read your mind. If you have 500 classes in your project, Spring does not automatically turn all 500 into Beans. It needs you to explicitly mark which classes it should take control of.

The Solution:
We use Stereotype Annotations to tell Spring, "Hey, take control of this class and make it a Bean." When Spring starts, it scans your code, finds these annotations, and creates the beans.

Here are the three most frequently used annotations in the industry:

@Component

This is the generic annotation for any Spring-managed component. If you have a utility class or a generic helper, you use this.

java
import org.springframework.stereotype.Component;

@Component
public class PasswordHasher {
    public String hash(String password) {
        // Hashing logic
        return "hashed_" + password;
    }
}

@Service

This is a specialization of @Component. It does exactly the same thing technically, but it tells other developers: "This class holds business logic."

java
import org.springframework.stereotype.Service;

@Service
public class UserService {
    public void registerUser(String username) {
        System.out.println("Registering user: " + username);
    }
}

@Repository

Another specialization of @Component. This tells developers: "This class interacts with the database." Under the hood, Spring also adds some extra magic to @Repository to automatically translate database exceptions into Spring-friendly exceptions.

java
import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {
    public void save(String username) {
        System.out.println("Saving " + username + " to database...");
    }
}

(Fun fact: If you try to create a new instance of a Spring Bean yourself using the new keyword, a senior Java architect somewhere sheds a single tear. Let Spring do it!)


3. Wiring it all Together: Mastering @Autowired and Constructor Injection 🔌

Definition:
Dependency Injection (DI) is a pattern where an object receives its dependencies from an external source (the Spring container) rather than creating them itself.

The Problem:
We have told Spring to create our UserService Bean and our UserRepository Bean. But UserService needs to talk to UserRepository to save a user. How do we connect them without using new?

The Solution:
We ask Spring to inject the dependencies. There are a few ways to do this, but the industry standard is Constructor Injection.

The Old Way: Field Injection (Do not do this)

Historically, developers used the @Autowired annotation directly on the field.

java
@Service
public class UserService {

    @Autowired // ❌ Highly discouraged in modern Spring!
    private UserRepository userRepository;

    public void registerUser(String username) {
        userRepository.save(username);
    }
}

Why is this bad? Because it makes testing a nightmare. You cannot easily test UserService in isolation without starting up the entire Spring framework, because there is no way to pass a mock UserRepository into a private field.

The Industry Standard: Constructor Injection

The correct, modern way to wire beans together is through the constructor. You don't even need the @Autowired annotation if your class only has one constructor (Spring is smart enough to figure it out).

java
@Service
public class UserService {

    // Make the dependency 'final' so it cannot be changed after creation
    private final UserRepository userRepository;
    private final PasswordHasher passwordHasher;

    // Spring automatically calls this constructor and injects the dependencies!
    public UserService(UserRepository userRepository, PasswordHasher passwordHasher) {
        this.userRepository = userRepository;
        this.passwordHasher = passwordHasher;
    }

    public void registerUser(String username, String rawPassword) {
        String safePassword = passwordHasher.hash(rawPassword);
        userRepository.save(username);
    }
}

Real-life Scenario:
Think of Constructor Injection like buying a car. You (the UserService) don't build the engine (UserRepository). You tell the dealership, "I cannot exist without an engine. When you hand me the keys, the engine must already be installed." Because the engine is final, no one can pop the hood and steal it while you are driving.

(Industry tip: Many developers use the Lombok library's @RequiredArgsConstructor annotation to automatically generate this constructor, saving lines of code. But under the hood, it's doing exactly what you see above).


4. Bean Scopes and Lifecycles: How Long Does a Bean Live? ⏳

Definition:
Bean Scope determines the lifecycle, visibility, and quantity of a bean instance within the Spring container.

The Problem:
If 10,000 users hit your website at the same time, and they all trigger the UserService, does Spring create 10,000 copies of UserService in memory? If it does, your server will crash immediately due to memory exhaustion.

The Solution:
Spring uses Scopes.

1. Singleton Scope (The Default & Industry Standard)

By default, every Bean in Spring is a Singleton. This means the ApplicationContext creates exactly one instance of the object when the application starts. Every single time a request comes in, Spring hands out that exact same instance.

Because of this, your Beans must be stateless.

Rule of thumb: Never store user-specific data (like String loggedInUser) as a class variable inside a @Service or @Component. Since it's a Singleton, User B will suddenly see User A's data! Only store dependencies (like Repositories) in class variables.

2. Prototype Scope (Rarely Used)

If you specifically tell Spring you want a new object every single time it is requested, you use the Prototype scope.

java
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype")
public class ShoppingCart {
    // Spring will create a brand new ShoppingCart object 
    // every time this is injected somewhere.
}

Note: In modern REST API development, you will rarely use Prototype scope. Keep 99% of your beans as Singletons.

The Lifecycle Hooks: @PostConstruct and @PreDestroy

Sometimes you need to run some code right after Spring finishes building the Bean and injecting its dependencies, or right before the application shuts down.

java
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.springframework.stereotype.Service;

@Service
public class CacheService {

    @PostConstruct
    public void init() {
        System.out.println("Bean is fully created and dependencies are wired! Loading cache...");
    }

    @PreDestroy
    public void cleanup() {
        System.out.println("Application is shutting down. Clearing cache to prevent memory leaks...");
    }
}

Summary

You have just mastered the core engine of Spring! Let's recap the flow:

  1. Spring starts up and creates the ApplicationContext (the manager).
  2. It looks for classes marked with @Component, @Service, or @Repository.
  3. It turns those classes into Beans (usually as single Singleton instances to save memory).
  4. It reads the constructors of those Beans and uses Dependency Injection to wire them all together seamlessly.

You are now ready to build decoupled, highly testable, and robust enterprise applications!


References for Extra Reading 📚

Challenge

You have been given three tightly-coupled Java classes: UserReportController, BusinessLogicService, and UserDataRepository. Your task is to refactor this code to use Spring's Inversion of Control (IoC) and Dependency Injection (DI) principles.

Your Tasks:

  1. Annotate the UserDataRepository class to be managed by Spring as a repository bean.
  2. Inside UserDataRepository, add a public void method named loadInitialData that will be executed by Spring immediately after the bean is constructed and all dependencies are injected. Annotate it appropriately.
  3. Annotate the BusinessLogicService class to be managed by Spring as a service bean.
  4. Refactor BusinessLogicService to use constructor injection. Remove the direct instantiation of UserDataRepository. Instead, declare a private final field for UserDataRepository and initialize it via a public constructor.
  5. Annotate the UserReportController class to be managed by Spring as a generic component bean.
  6. Refactor UserReportController to use constructor injection. Remove the direct instantiation of BusinessLogicService. Instead, declare a private final field for BusinessLogicService and initialize it via a public constructor.

Expected result

The final code should correctly implement Spring's dependency injection to create a loosely-coupled application.

  • The UserDataRepository class must be annotated with @Repository.
  • Inside UserDataRepository, there must be a public method void loadInitialData() annotated with @PostConstruct.
  • The BusinessLogicService class must be annotated with @Service.
  • BusinessLogicService must have a private final UserDataRepository field and a public constructor that accepts a UserDataRepository object to initialize the field.
    The line new UserDataRepository() should be removed.
  • The UserReportController class must be annotated with @Component.
  • UserReportController must have a private final BusinessLogicService field and a public constructor that accepts a BusinessLogicService object to initialize the field.
    The line new BusinessLogicService() should be removed.
java

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.