Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 119 ยท Spring Framework

Spring Framework Introduction

What the Spring Framework is and why most Java backends use it - inversion of control, the module map, Spring vs Jakarta EE and Spring Boot, and Spring 7 / Boot 4.

Open the code of almost any Java backend written in the last fifteen years and you will find Spring: @Service and @Autowired in the classes, spring-boot-starter-web in the build file, a main method that calls SpringApplication.run. Spring is the most widely used framework in the Java world, and knowing it is part of nearly every Java backend job description.

Spring can feel like magic at first. Objects appear in your constructors without anyone calling new, methods become transactional because of an annotation, and a web server starts from a single line. This chapter takes the magic apart. In this lesson you will see what problem Spring solves, which parts it is made of, how it relates to Jakarta EE and Spring Boot, and which versions are current. The following lessons build each core mechanism by hand (dependency injection, bean configuration, AOP proxies) before showing the Spring version.

Spring itself can't run in our sandbox, so Spring code in this chapter is shown read-only with its output described. Every concept also comes with runnable plain-Java examples that do the same thing on a small scale.

What Spring is

Spring is an open-source application framework for Java (and Kotlin). It began with Rod Johnson's 2002 book on J2EE design, whose sample code became Spring 1.0 in 2004. At the time, enterprise Java meant heavyweight EJB components, XML deployment descriptors and an application server just to run a unit test. Spring's promise was the opposite: write plain Java objects (POJOs), and let a lightweight container connect them and add services like transactions from the outside.

That promise rests on three ideas:

  1. Inversion of Control (IoC) and dependency injection. Your classes don't create or look up the objects they depend on. The Spring container creates them, wires them together and manages their lifecycle.
  2. Aspect-oriented programming (AOP). Cross-cutting behavior such as transactions, security checks, caching and metrics is added around your methods by proxies, so business code stays focused.
  3. Portable service abstractions. Consistent APIs over messy infrastructure: one transaction API for JDBC, JPA and JTA; one exception hierarchy for all databases; templates and clients that remove boilerplate.

Inversion of control

In a normal program, your code is in charge: main creates objects, objects create the other objects they need, and so on. With inversion of control, a framework is in charge of that wiring, and your code is called by it. You have already seen small examples of IoC: a servlet container calls your doGet, and JUnit creates your test class and calls your @Test methods.

The specific form of IoC that Spring is built on is dependency injection: an object declares what it needs (usually as constructor parameters) and receives it. Look at what goes wrong without it:

Java A class that builds its own dependencies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

ReportServiceV1 is welded to one implementation: you can't test it, reuse it with another database, or replace the repository with a caching one, without editing the class. ReportServiceV2 only states its needs. Someone else decides what to pass in. In a test that someone is you; in a running application it is the Spring container.

The container: ApplicationContext

Spring's IoC container is the ApplicationContext. You give it a description of your objects (annotated classes, @Bean methods, or, in older projects, XML), and it creates them in the right order, injects their dependencies and keeps them for the lifetime of the application. Objects managed by the container are called beans.

Here is the smallest complete Spring program, using the spring-context module:

Java
package com.example.reports;

import org.springframework.context.annotation.*;
import org.springframework.stereotype.*;
import java.util.List;

interface SalesRepository {
    List<Integer> salesFor(String month);
}

@Repository
class InMemorySalesRepository implements SalesRepository {
    public List<Integer> salesFor(String month) { return List.of(120, 80, 45); }
}

@Service
class ReportService {
    private final SalesRepository repository;

    ReportService(SalesRepository repository) {   // injected by Spring
        this.repository = repository;
    }

    int total(String month) {
        return repository.salesFor(month).stream().mapToInt(Integer::intValue).sum();
    }
}

@Configuration
@ComponentScan
public class ReportsApp {
    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(ReportsApp.class)) {
            ReportService service = context.getBean(ReportService.class);
            System.out.println("total = " + service.total("2026-09"));
        }
    }
}

Running it prints total = 245. @ComponentScan makes Spring search the com.example.reports package for classes annotated with @Component or its specializations (@Service, @Repository, @Controller), create one instance of each, and satisfy ReportService's constructor with the matching SalesRepository. Nobody calls new.

The core of such a container is surprisingly small. This runnable version registers recipes ("how to build a bean") and creates each bean once, on first request:

Java A tiny application context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Asking for the controller made the context create the whole chain: the controller's recipe asked for the service, whose recipe asked for the repository, so the objects were finished in dependency order (repository, service, controller). The second request returned the same object. That is the default singleton scope in Spring: one shared instance per container. Spring's error for a missing bean, NoSuchBeanDefinitionException, plays the role of our NoSuchElementException. The real container adds what our toy lacks: discovering classes by scanning, choosing constructors by reflection, scopes, lifecycle callbacks, proxies and very good error messages. You will build several of those pieces yourself in the next lessons.

Removing boilerplate: templates and exception translation

The third idea, service abstractions, is easiest to see with JDBC. Every JDBC method you have written repeats the same steps: get a connection, prepare a statement, bind parameters, loop over the result set, close everything, and turn SQLException into something callers can handle. Spring's JdbcTemplate (and the newer fluent JdbcClient) does all of that, and you supply only the SQL and the row mapping:

Java
@Repository
class BookRepository {
    private final JdbcClient jdbc;

    BookRepository(JdbcClient jdbc) { this.jdbc = jdbc; }

    List<Book> cheaperThan(BigDecimal max) {
        return jdbc.sql("SELECT id, title, price FROM book WHERE price < ? ORDER BY price")
                   .param(max)
                   .query(Book.class)           // maps columns to the record's components
                   .list();
    }
}

Spring also translates exceptions: instead of an SQLException with a vendor-specific code, you get an unchecked exception from one portable hierarchy, such as DuplicateKeyException or DataIntegrityViolationException, whichever database you use. Here is the same idea in a few lines of plain Java over H2:

Java A mini JdbcTemplate with exception translation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The business code now reads like what it does. Callers can catch DuplicateKeyException without knowing that the database is H2 or that its code is 23505, and nobody can forget to close a statement. Spring applies this pattern everywhere: JdbcClient, RestClient, JmsTemplate, KafkaTemplate, TransactionTemplate.

The Spring module map

"Spring" names both a framework and a family of projects built on it.

Spring Framework (the core), split into modules you can use separately:

Area Modules and features
Core container spring-core, spring-beans, spring-context: IoC, dependency injection, events, resources, validation, the Environment and profiles
AOP spring-aop (proxy-based aspects), AspectJ integration
Data access spring-jdbc (JdbcTemplate, JdbcClient), spring-tx (transactions, @Transactional), spring-orm (JPA/Hibernate integration)
Web (servlet) spring-web, spring-webmvc: Spring MVC, @RestController, RestClient
Web (reactive) spring-webflux: non-blocking web stack on Reactor
Testing spring-test: the TestContext framework, MockMvc

Spring projects on top of the framework (each with its own releases):

  • Spring Boot: auto-configuration, starters, an embedded server and production features. It is how most Spring applications are created today (see Spring Boot Introduction).
  • Spring Data: repositories for JPA, JDBC, MongoDB, Redis, Elasticsearch and more (Spring Data JPA).
  • Spring Security: authentication and authorization (Spring Security).
  • Spring Cloud: configuration, service discovery, gateways and resilience for distributed systems (Microservices).
  • Others you will meet: Spring Batch (batch jobs), Spring Integration (enterprise integration patterns), Spring for Apache Kafka, Spring AMQP, Spring Modulith (modular monoliths), Spring Authorization Server and Spring AI.

Spring, Spring Boot and Jakarta EE

Spring vs Spring Boot. Spring Framework provides the mechanisms; Spring Boot makes decisions for you. Without Boot, you choose and configure every library: the DataSource, the transaction manager, Jackson, the servlet container. With Boot, adding spring-boot-starter-web gives you a configured Spring MVC application on an embedded Tomcat, and you override only what you need. Boot does not replace Spring; it is Spring plus sensible defaults.

Spring vs Jakarta EE. Jakarta EE is a set of specifications (Servlet, Persistence, Bean Validation, CDI, REST and more) implemented by application servers like WildFly, GlassFish, Open Liberty and Payara. The two are not simple rivals:

Spring Jakarta EE (full platform)
What it is One framework family, one vendor-led open-source project Vendor-neutral specifications with several implementations
Dependency injection Spring's container CDI
Runs on Any JVM; Boot embeds Tomcat, Jetty or Undertow An application server, or a runtime like Quarkus, Helidon or Open Liberty
Uses Jakarta specs? Yes: Servlet, Persistence (JPA), Bean Validation, Mail and others It is the specs

Spring builds on many Jakarta EE APIs. A Spring Boot web application runs on a Servlet container and stores data through Jakarta Persistence. What Spring replaces is mainly CDI and EJB with its own container. Concepts carry over in both directions, which is why this course teaches the Jakarta pieces first.

Versions: Spring Framework 7 and Spring Boot 4

Release Year Highlights
Spring Framework 5 / Boot 2 2017โ€“2018 Java 8 baseline, WebFlux, Kotlin support; still the old javax.* packages
Spring Framework 6 / Boot 3 Nov 2022 Java 17 baseline, Jakarta EE 9+ (jakarta.* packages), AOT processing and GraalVM native images, observability with Micrometer
Spring Framework 7 / Boot 4 Nov 2025 Java 17 baseline (Java 25 recommended), Jakarta EE 11, JSpecify null-safety annotations, built-in API versioning and resilience features (@Retryable, @ConcurrencyLimit), Jackson 3 support; Boot 4 modularizes its auto-configuration

Two practical consequences:

  • The javax to jakarta switch. Code and libraries written for Spring 5 / Boot 2 use javax.persistence, javax.servlet and so on. Spring 6 and later need jakarta.*. When you copy an older example, this is the first thing to fix.
  • Pick the current generation for new projects. This course shows Spring Framework 7 and Spring Boot 4 style. Almost everything also applies to Spring 6 / Boot 3, which many production systems still run. Where the versions differ, the lessons say so.

Spring's open-source releases are supported for a limited time (each minor version for roughly a year after the next one appears), with longer commercial support available. Plan regular upgrades: staying within one generation is usually a small change, while jumping several years at once is a project.

How to learn Spring without drowning

Spring's documentation is huge, and most of it is optional. Learn it in this order, which is also the order of this chapter and the next:

  1. Dependency injection and beans. Everything else is built on the container.
  2. Configuration and profiles. How beans are defined and how an app adapts to dev, test and production.
  3. AOP and proxies. Not to write aspects every day, but to understand @Transactional, @Cacheable and @Async, and why they sometimes don't apply.
  4. Spring MVC and Spring Boot. Web endpoints, JSON, validation, error handling.
  5. Spring Data, Security and testing. The pieces almost every real application uses.

Whenever something seems magical, ask two questions: "which bean does this?" and "which proxy is in front of this method?". Most Spring mysteries are answered by one of them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "inversion of control" mean in Spring?

    With IoC, the container is in charge of creating objects and connecting them. Dependency injection is the form Spring uses.
  2. 2. In the tiny context example, what happens when you call getBean(ReportController.class) the second time?

    Beans are singletons by default, so the context creates each one once and returns the cached instance afterwards.
  3. 3. Which statement about Spring Boot is correct?

    Spring Boot is opinionated configuration on top of Spring Framework, not a replacement for it.
  4. 4. You copy a Spring Boot 2 example that imports javax.persistence.Entity into a Spring Boot 4 project. What is the likely problem?

    Spring Framework 6 moved to Jakarta EE 9+, where the APIs live in jakarta.* packages.
  5. 5. What does Spring's exception translation give you?

    Spring maps vendor-specific SQL errors onto one portable, unchecked DataAccessException hierarchy.

Summary

  • Spring is an application framework built on inversion of control: its container creates your objects (beans) and injects their dependencies.
  • Its other pillars are AOP (behavior added around methods by proxies) and service abstractions (templates, one transaction API, portable exceptions).
  • The ApplicationContext is the container; beans are singletons by default.
  • Spring Framework has modules for the core container, AOP, data access, web (MVC and WebFlux) and testing. Projects such as Spring Boot, Spring Data, Spring Security and Spring Cloud build on it.
  • Spring uses many Jakarta EE specifications (Servlet, JPA, Bean Validation) but replaces CDI and EJB with its own container.
  • Current generation: Spring Framework 7 and Spring Boot 4 (Java 17+, Jakarta EE 11). Spring 6 / Boot 3 introduced the jakarta.* packages.

Next: Dependency Injection and Inversion of Control builds a working DI container with reflection, then shows how Spring does the same.