Skip to content
DmitryDerkachPublic

About

Spring course (dmdev, 2022) replayed step by step: IoC by hand, bean lifecycle, BeanFactoryPostProcessors, own BeanPostProcessors with JDK proxies, profiles, properties, events, Spring Data JPA. One command, tests, CI, Codespaces

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

Spring course (dmdev, 2022) — what Spring does under the hood

Build, run and test Spring under the hood Open in GitHub Codespaces

The page "Spring under the hood"

My code from the Spring course by dmdev, December 2022: Spring Boot, the IoC container, the bean lifecycle, BeanFactoryPostProcessors, my own BeanPostProcessors that build JDK proxies, Java configuration, profiles, @Conditional, @ConfigurationProperties, events, Spring Data JPA and tests. It continues my Hibernate course. The entities are the same (User, Company, Chat, Payment), now managed by Spring.

The repository is one commit of 2022-12-26, "ALL WORKS!!!", the state after the last lesson. During the course every lesson overwrote the code of the previous one. In 2026 the topics were brought back as steps that run one by one (./run.sh bpp), the bugs found by running it were fixed, and it got tests, a one-command start and the page above. The course had no description in the repository, so the topics below are reconstructed from the code and its comments.

Three ways to see it work

How What you get
🌐 In the browser, nothing to install dmitryderkach.github.io/Spring Every step of the course: its code, the classes of 2022 it uses and the real output, recorded by GitHub Actions from this commit. Plus the bean lifecycle and a call walked through the proxy chain
☁️ In GitHub Codespaces Open in Codespaces A cloud machine with JDK 17 and Docker runs ./run.sh and the whole course. Then try ./run.sh bpp, ./run.sh app, ./run.sh test in its terminal
💻 On your machine ./run.sh (Git Bash / Linux / macOS) or .\run.ps1 (PowerShell) The same, with JDK 11+ and Docker. See How to run

The course

# Step (./run.sh <step>) Topic Classes of 2022 (and 2026)
1 ioc IoC "by hand", before Spring: a container creates objects and their constructor dependencies ioc/Container (a stub in 2022, finished in 2026), IocExample (2026)
2 context @SpringBootApplication, the ApplicationContext, @PostConstruct / @PreDestroy. The original main ApplicationRunner, database/pool/ConnectionPool
3 bfpp BeanFactoryPostProcessor: bean definitions exist, beans do not. PriorityOrdered before Ordered bfpp/LogBeanFactoryPostProcessor, bfpp/VerifyPropertyBeanFactoryPostProcessor
4 config Java configuration: @Bean, @Scope(prototype), @Qualifier, @Import, proxyBeanMethods configuration/ApplicationConfiguration, database/repository/UserRepository
5 profiles @Profile("prod|web") and @Conditional with my own Condition configuration/condition/JpaCondition, JpaConfiguration, web/config/WebConfiguration
6 properties @Value("${...}") and @ConfigurationProperties + @ConstructorBinding (lists and maps from yaml) configuration/DatabaseProperties, application.yaml
7 bpp Own BeanPostProcessors: @InjectBean (my @Autowired), @Transaction and @Auditing (JDK proxies) bpp/*, database/repository/CompanyCrudRepository (2026, restored)
8 events ApplicationEventPublisher and @EventListener with a SpEL condition service/CompanyService, listener/entity/*
9 jpa Spring Data JPA: query methods, @NamedQuery, @ElementCollection, TransactionTemplate database/repository/CompanyRepository, database/entity/*
./run.sh test Tests: Mockito unit test, @SpringBootTest with my own @IT annotation, @SpyBean, constructor injection in tests src/test/java/...
flowchart LR
    H["Hibernate course<br/>(previous repository)"]:::prev --> IOC["1 ioc<br/>Container by hand"]
    IOC --> CTX["2 context<br/>ApplicationContext<br/>lifecycle"]
    CTX --> BFPP["3 bfpp<br/>bean definitions"]
    BFPP --> CFG["4 config<br/>@Bean, scopes,<br/>proxyBeanMethods"]
    CFG --> PRF["5 profiles<br/>@Profile, @Conditional"]
    PRF --> PROP["6 properties<br/>@Value,<br/>@ConfigurationProperties"]
    PROP --> BPP["7 bpp<br/>own BeanPostProcessors,<br/>JDK proxies"]:::star
    BPP --> EV["8 events<br/>@EventListener"]
    EV --> JPA["9 jpa<br/>Spring Data JPA"]
    JPA --> T["tests<br/>@SpringBootTest, @IT"]
    classDef prev fill:#EEF1EA,stroke:#7A857D,color:#18261C
    classDef star fill:#FBF1DC,stroke:#B9831A,color:#18261C,stroke-width:2px
    classDef default fill:#E3F1D8,stroke:#3F7A1F,color:#18261C
Loading

On the page every step has its code, the classes of the course it uses and the output, coloured by who printed it:

A step of the course on the page

Under the hood

Who reads the annotations

An annotation is only a label. Every one of them works because some class of Spring looks for it at a certain moment of a bean's life. In this course I wrote such classes myself, and they hook into the same moments:

flowchart TB
    subgraph DEF["Bean definitions only (no objects yet)"]
        direction LR
        A["@ComponentScan, @Bean,<br/>@Configuration<br/>→ BeanDefinition"] --> B["BeanFactoryPostProcessor<br/>LogBeanFactoryPostProcessor<br/>(PriorityOrdered first)"]
    end
    subgraph BEAN["For every bean"]
        direction LR
        C["constructor<br/>+ @Value"] --> D["postProcessBeforeInitialization<br/>InjectBeanPostProcessor fills<br/>@InjectBean fields"]
        D --> E["@PostConstruct<br/>ConnectionPool.init()"]
        E --> F["postProcessAfterInitialization<br/>Transaction / Auditing BPP<br/>return a JDK proxy"]
    end
    subgraph END["context.close()"]
        G["@PreDestroy<br/>(singletons only)"]
    end
    DEF ~~~ BEAN ~~~ END
    B --> C
    F --> G
    style DEF fill:#E2ECF8,stroke:#3569A8,color:#18261C
    style BEAN fill:#E3F1D8,stroke:#3F7A1F,color:#18261C
    style END fill:#EDF0EC,stroke:#7A857D,color:#18261C
Loading

The page shows each stage with the line the recorded run printed there:

Bean lifecycle on the page

One call, four objects

context.getBean("companyCrudRepository") does not return a CompanyCrudRepository. TransactionBeanPostProcessor and AuditingBeanPostProcessor each replaced the bean with a JDK proxy in postProcessAfterInitialization, one proxy inside the other. A call goes through all of them:

sequenceDiagram
    autonumber
    participant R as CourseRunner (2026)
    participant T as $Proxy of TransactionBeanPostProcessor (2022)
    participant A as $Proxy of AuditingBeanPostProcessor (2022)
    participant C as CompanyCrudRepository (2026)
    participant D as CompanyRepository (Spring Data proxy)
    participant DB as PostgreSQL
    R->>T: findById(1)
    Note over T: prints "Open transaction"
    T->>A: method.invoke(bean, args)
    Note over A: prints "Audit method: findById", starts a timer
    A->>C: method.invoke(bean, args)
    Note over C: pool1 was filled by InjectBeanPostProcessor
    C->>D: companyRepository.findById(1)
    D->>DB: select ... from company where id=?
    DB-->>D: Google
    D-->>C: Optional[Company]
    C-->>A: Optional[Company]
    Note over A: prints "Time execution: ..."
    A-->>T: Optional[Company]
    Note over T: prints "Close transaction"#59; on an exception "Rollback transaction" first
    T-->>R: Optional[Company]
Loading

The real output of ./run.sh bpp (the times and the proxy class name differ from run to run):

bean 'companyCrudRepository' is jdk.proxy2.$Proxy112 (a JDK proxy, not CompanyCrudRepository itself)
--- repository.findById(1):
Open transaction
Audit method: findById
INFO  CompanyCrudRepository : findById method... (pool1 injected by @InjectBean: ConnectionPool [username=postgres, poolSize=12])
Hibernate:
    select
        company0_.id as id1_1_0_,
        company0_.name as name2_1_0_
    from
        company company0_
    where
        company0_.id=?
Time execution: 61814700
Close transaction
--- result: Google
--- repository.delete(null) - the real method throws:
Open transaction
Audit method: delete
INFO  CompanyCrudRepository : delete method...
Time execution: 178300
Rollback transaction
Close transaction
--- caught IllegalArgumentException: Company must not be null

Why both BPPs remember the class in postProcessBeforeInitialization (as written in 2022): by the time the second one gets to postProcessAfterInitialization, the bean may already be the proxy of the first one. A proxy has no @Auditing annotation, but the remembered class still has it.

A JDK proxy can only implement interfaces. That is why the restored CompanyCrudRepository implements my own CrudRepository<Integer, Company>, the interface the commented-out lines of 2022 refer to. For a class without interfaces Spring makes a CGLIB subclass instead. You can see two of them in step 4: the @Configuration class (proxyBeanMethods = true) and every @Repository, which gets a proxy that turns exceptions into Spring's DataAccessException.

One call walked through the proxies on the page

proxyBeanMethods: four calls, one bean

@Bean
public UserRepository userRepository3() {
    var connectionPool1 = pool3();
    var connectionPool2 = pool3();
    var connectionPool3 = pool3();
    return new UserRepository(pool3());
}

With @Configuration(proxyBeanMethods = true) Spring does not use ApplicationConfiguration itself. It uses a CGLIB subclass (ApplicationConfiguration$$EnhancerBySpringCGLIB$$...) that intercepts pool3() and returns the pool3 bean from the context. Step 4 prints userRepository3() calls pool3() four times, but gets the pool3 bean: true. With proxyBeanMethods = false these would be four plain Java calls and four new objects that are not beans.

My classes and Spring's classes

In this course (2022) The real thing in Spring
Container.get(Class) ApplicationContext.getBean(Class): DefaultListableBeanFactory creates beans from definitions, resolves constructor arguments and caches singletons
@InjectBean + InjectBeanPostProcessor @Autowired + AutowiredAnnotationBeanPostProcessor: the same reflection on fields, plus constructors and setters
@Transaction + TransactionBeanPostProcessor @Transactional + TransactionInterceptor: a proxy that really begins, commits or rolls back a database transaction
@Auditing + AuditingBeanPostProcessor An @Aspect with @Around (Spring AOP), or Micrometer's @Timed
LogBeanFactoryPostProcessor PropertySourcesPlaceholderConfigurer (resolves ${...} in definitions), ConfigurationClassPostProcessor (turns @Configuration classes into definitions)
JpaCondition All of Spring Boot's auto-configuration: @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty

What I wrote in 2022 and what was added in 2026

The page and the steps show both, so it helps to be exact:

Written in 2022 Added in 2026
All entities, repositories, services, configurations, ConnectionPool, the three BeanPostProcessors and their annotations, both BeanFactoryPostProcessors (with an empty loop and System.out.println()), the Container stub, ApplicationRunner, the tests, application.yaml CourseRunner (the steps), IocExample, the body of Container.get, the output of the two BFPPs, CrudRepository + CompanyCrudRepository (restored from the commented-out CrudRepository<Integer, Company> lines, so that the BPPs have a bean to work on), CourseFeaturesIT, WebProfileIT, ContainerTest, everything in db/, site/, .github/, .devcontainer/, the scripts

In the code, every change of 2026 is marked: // fix 2026: ... above a fixed line, // 2026: ... above an addition, /* Описание (2026): ... */ above every class (a short description in Russian). My own comments of 2022 are in Russian too and are kept.

Project structure

Spring/
├── pom.xml                       Spring Boot 2.7.18 parent, Java 11, the Boot plugin, Failsafe for *IT
├── docker-compose.yml            PostgreSQL 18 on port 5438 (database spring_database)
├── run.sh / run.ps1              one command for everything (see below)
├── db/
│   ├── 01_schema.sql             tables (re-runnable: drops them first)
│   └── 02_data.sql               3 companies, 5 users, payments, chats
├── src/main/java/spring/
│   ├── ApplicationRunner.java    the original main of 2022
│   ├── CourseRunner.java         2026: the course step by step
│   ├── ioc/                      Container (IoC by hand), IocExample
│   ├── bfpp/                     two BeanFactoryPostProcessors
│   ├── bpp/                      @InjectBean, @Transaction, @Auditing and their BeanPostProcessors
│   ├── configuration/            Java configuration, DatabaseProperties, @Conditional
│   ├── database/entity|pool|repository/
│   ├── dto/  listener/  service/
├── src/main/java/web/config/     WebConfiguration (@Profile("web"))
├── src/main/resources/           application.yaml, spring.properties
├── src/test/java/spring/         unit tests (*Test) and integration tests (*IT)
├── site/                         the GitHub Pages page and its recorder (capture.py)
└── .devcontainer/                GitHub Codespaces

How to run

You need: JDK 11 or newer (checked on 11, 17 and 21) and Docker (Docker Desktop on Windows and macOS). Maven is not needed: ./mvnw downloads Maven 3.9.16 on the first run.

./run.sh            # Git Bash on Windows, Linux, macOS
.\run.ps1           # Windows PowerShell 5.1 or PowerShell 7

The script starts PostgreSQL in Docker (port 5438), recreates the tables and the demo data, builds the jar and runs all nine steps. The database is reset before every run, so the output is the same every time.

Command What it does
./run.sh the whole course, step by step
./run.sh bpp one step by name (ioc, context, bfpp, config, profiles, properties, bpp, events, jpa)
./run.sh 7 the same step by its number; several: ./run.sh ioc bpp
./run.sh app the original ApplicationRunner of 2022, with the Spring banner
./run.sh test unit tests (mvnw test: 3) and integration tests with the database (mvnw verify: 18)
./run.sh reset recreate the tables and the demo data
./run.sh stop stop the database and delete its volume
./run.sh help this list

.\run.ps1 takes the same arguments. An unknown step prints the list of steps and exits with code 1.

Without the scripts

docker compose up -d --wait                       # PostgreSQL 18 on localhost:5438
./mvnw package -DskipTests                        # target/spring-course.jar
java -jar target/spring-course.jar                # the course (CourseRunner); add a step name: ... bpp
java -Dloader.main=spring.ApplicationRunner -jar target/spring-course.jar   # the original main
./mvnw verify                                     # all tests
docker compose down -v

The jar is an executable Spring Boot jar with the ZIP layout. That is what makes -Dloader.main able to choose another main class.

In an IDE

Import as a Maven project. Lombok needs annotation processing (IntelliJ IDEA asks for it; in Eclipse install Lombok). Start the database with docker compose up -d --wait, then run spring.CourseRunner or spring.ApplicationRunner. Integration tests (*IT) need the database too.

Your own PostgreSQL

Create a database, run db/01_schema.sql and db/02_data.sql, and override the connection on the command line:

java -jar target/spring-course.jar --spring.datasource.url=jdbc:postgresql://localhost:5432/mydb \
  --spring.datasource.username=me --spring.datasource.password=secret

For the tests: ./mvnw verify -Dspring.datasource.url=....

Troubleshooting

  • Port 5438 is busy: DB_PORT=5439 ./run.sh (PowerShell: $env:DB_PORT = "5439"; .\run.ps1). The script passes the new URL to the application and the tests.
  • Schema-validation: missing column ... at start: hbm2ddl.auto=validate compares the entities with the tables. The database has an old or changed schema: ./run.sh reset.
  • Docker is not running: docker compose up fails with a message about the Docker daemon. Start Docker Desktop and try again.
  • ????? instead of Cyrillic when running java -jar yourself: add -Dstdout.encoding=UTF-8 (the scripts do it).

Versions: why Spring Boot 2.7.18

The course was written on Spring Boot 2.6.2. It is updated to 2.7.18, the last free (open-source) release of Spring Boot 2.x (November 2023). The code stays the code of the course: javax.persistence, javax.annotation, @ConstructorBinding.

Every branch of Spring Boot gets free updates for a limited time. After that, fixes are released only to companies with a paid subscription. So there will be no new free release of 2.7.x or of Spring Framework 5.3 underneath it. For this project that is acceptable:

  • it is a course that starts, prints and stops, not a server that accepts requests;
  • most of the later security fixes in Spring 5.3 are in the web part (spring-web, spring-webmvc), which this project does not use;
  • the libraries with known vulnerabilities are updated on their own, over what Boot 2.7.18 brings: PostgreSQL JDBC 42.7.14 (instead of 42.3.1: CVE-2022-21724, CVE-2024-1597) and SnakeYAML 2.7 (instead of 1.29: CVE-2022-1471). CI checks that the old versions do not come back.

Moving to Spring Boot 3 would mean: javax.* → jakarta.* in every import, Java 17+, Hibernate 6 (different SQL aliases), and @ConstructorBinding is no longer needed on a class with one constructor. Every step would have to be checked again, and the code would no longer match the lessons.

2026 clean-up

Bugs found by running the code

  • application.yaml: the Hibernate keys were one level too high, so spring.jpa.properties.hibernate was empty. show_sql worked by chance (as spring.jpa.show-sql), but hbm2ddl.auto: validate and format_sql were silently ignored. Checked on the 2022 code: with a column dropped, the application still started. Now it fails as it should.
  • LazyInitializationException in CompanyService.findById outside a transaction: the event listener prints Company, and Lombok's toString reads the lazy locales after the session is closed. The integration test did not notice because @IT is @Transactional. Fixed with @Transactional(readOnly = true); a test runs it without a transaction now.
  • The JDK proxies of TransactionBeanPostProcessor and AuditingBeanPostProcessor rethrew the InvocationTargetException of method.invoke, so the caller got UndeclaredThrowableException instead of the real exception. They unwrap it now.
  • @InjectBean used getBean(type), which fails with three ConnectionPool beans (pool1, pool2, pool3). With several candidates it now picks the bean named like the field, the rule @Autowired uses.
  • @Transaction, @Auditing and @InjectBean were not used on any class, so the three BeanPostProcessors did nothing. CompanyCrudRepository (restored, see above) uses them.
  • src/main/resources/sql/data.sql started with NSERT. It was an unused copy of Scripts/: both are now db/01_schema.sql + db/02_data.sql, made re-runnable.
  • java -jar failed with "no main manifest attribute", and Maven ran 1 test of 7: all plugins were in <pluginManagement>, which only configures and does not apply them. The Boot plugin now builds an executable jar, and Failsafe runs the *IT tests.
  • Tests that could run once: @Commit on CompanyRepositoryIT really wrote "Apple" into the database (the second run failed with a duplicate key), and delete() used a hard-coded id 7 that exists only after several committed runs. Now every test is rolled back and creates what it deletes. The empty UserServiceIT.test() checks something now.
  • The listener printed Entityspring.listener... (no space).

Brought back

  • Container.get (it returned null), the output of both BeanFactoryPostProcessors (an empty loop with a TODO of the course and System.out.println()), and the nine steps of CourseRunner.

Infrastructure

  • Spring Boot 2.6.2 → 2.7.18, PostgreSQL JDBC 42.7.14, SnakeYAML 2.7, Java 18 → 11 (runs on 11–21).
  • docker-compose.yml (PostgreSQL 18, port 5438), run.sh / run.ps1, Maven Wrapper 3.9.16.
  • Tests: 3 unit tests and 18 integration tests (was 7, one of them run). CourseFeaturesIT covers every fix above and every step. Each fix was checked the other way round too: with the fix reverted, a test fails.
  • GitHub Actions on Java 11 / 17 / 21: tests, the whole course twice (the output must be the same), single steps, the original main, another port, the dependency versions. Then it records the course and deploys the page.
  • GitHub Codespaces (.devcontainer/), the page site/ with site/capture.py.

Housekeeping

  • Eclipse files (.classpath, .project, 14 files in .settings/) and workspace/.../target/... removed from git.
  • src/main/webapp (web.xml, MANIFEST.MF) removed: the project is a jar, and WebConfiguration is only a profile.
  • The local login and password dmitry_derkach / 1234 → postgres / postgres of the Docker database.
  • groupId dmitry → io.github.dmitryderkach.
  • Typos: package annotattion → annotation, «Автоматичеки» → «Автоматически».

Known issues

These are not bugs, they are how the course is:

  • ConnectionPool is a demo bean with @Value and lifecycle methods, not a pool. Real connections come from HikariCP, which Spring Boot configures by itself. The db: block of application.yaml (password: pass, url: postgres:5432) is demo data for @ConfigurationProperties and is not used to connect anywhere.
  • @Transaction only prints. The real transactions in steps 8 and 9 are Spring's @Transactional and TransactionTemplate.
  • My BeanPostProcessors make JDK proxies, so they work only for beans with interfaces.
  • UserService and WebConfiguration are empty. The course goes on with them after this commit.
  • Prototype beans (UserRepository) never get @PreDestroy: the context does not keep them.
  • Spring Boot 2.x gets no more free updates, see Versions.
  • The old local password 1234 is still in the history of 2022. It was a local development database only.

Credits

  • The course: dmdev, Spring course (2022).
  • The page uses the fonts Fraunces, Public Sans and JetBrains Mono from Google Fonts (SIL Open Font License).

About

Spring course (dmdev, 2022) replayed step by step: IoC by hand, bean lifecycle, BeanFactoryPostProcessors, own BeanPostProcessors with JDK proxies, profiles, properties, events, Spring Data JPA. One command, tests, CI, Codespaces

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages