Java NotesRohit’s interview study guide
Chapter 12

Spring Core: Dependency Injection and Spring Boot

What Spring actually does: it creates your objects and wires them together (dependency injection), and Spring Boot configures the infrastructure for you from what's on the classpath. Beans, component scanning, constructor injection, scopes, configuration and profiles, auto-configuration, the proxies behind @Transactional, and what happens when an app starts. Every example was run with Spring Boot 4.2.0 on Java 25.

Try it yourself. Every example is the starter project from chapter 11 plus the files shown: copy the starter's folder, save the files over it, and type the $ lines. Most examples here aren't web apps; they print something from a CommandLineRunner and exit. So their application.properties has four lines: the app's name, spring.main.web-application-type=none (don't start the web server, so the program ends), spring.main.banner-mode=off and logging.level.root=warn (hide the banner and the startup log, so you only see what the example prints). ./mvnw -q spring-boot:run compiles and runs the app, with Maven itself quiet (-q).

9 topics
Parts marked Advanced are extra depth. Skip them on a first read or a quick revision.

#Why Spring exists

Added

Every real application has a graph of objects: a controller needs a service, the service needs a repository and a payment client, the repository needs a database connection pool, which needs configuration. Somebody has to create all of them, in the right order, and hand each one the objects it needs.

In plain Java you do that by hand with new, usually in main. That's fine for five classes and painful for five hundred, and it hard-codes choices (which payment client? which database?) into the wiring code. Spring is a container that does the wiring for you. You mark your classes, declare what each one needs in its constructor, and Spring creates every object once, works out the order, and passes them in. That's inversion of control: your classes don't create their dependencies or look them up; they're given them. Handing them in is dependency injection (DI).

For a Node.js developer the closest picture is this: in Node, require("./db") gives every file the same module instance, so modules act as singletons and you wire things by importing them. That works, but it couples files to concrete implementations, and swapping one in a test needs tricks like jest.mock. NestJS is the Node framework that works like Spring (and was modelled on Angular, which got the idea from Spring): @Injectable() classes and constructor injection. If you've used NestJS or Angular services, you already know the shape.

The same classes wired two ways: by hand in plain Java on the left, and by Spring on the right (a file in the starter project, plus the four-line application.properties from the top of this chapter).

Main.java
interface PaymentGateway {
    String charge(long cents);
}

class CardGateway implements PaymentGateway {
    public String charge(long cents) {
        return "charged " + cents + " cents to the card";
    }
}

interface Notifier {
    void send(String message);
}

class EmailNotifier implements Notifier {
    public void send(String message) {
        IO.println("email: " + message);
    }
}

class OrderService {
    private final PaymentGateway payments;
    private final Notifier notifier;

    OrderService(PaymentGateway payments, Notifier notifier) {
        this.payments = payments;
        this.notifier = notifier;
    }

    void place(String item, long cents) {
        notifier.send(item + ": " + payments.charge(cents));
    }
}

void main() {
    var orders = new OrderService(new CardGateway(), new EmailNotifier());
    orders.place("Keyboard", 4999);
}
Terminal
$ java Main.java
email: Keyboard: charged 4999 cents to the card
src/main/java/com/example/shop/Orders.java
package com.example.shop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

interface PaymentGateway {
    String charge(long cents);
}

@Component
class CardGateway implements PaymentGateway {
    public String charge(long cents) {
        return "charged " + cents + " cents to the card";
    }
}

interface Notifier {
    void send(String message);
}

@Component
class EmailNotifier implements Notifier {
    public void send(String message) {
        System.out.println("email: " + message);
    }
}

@Service
class OrderService {
    private final PaymentGateway payments;
    private final Notifier notifier;

    OrderService(PaymentGateway payments, Notifier notifier) {
        this.payments = payments;
        this.notifier = notifier;
    }

    void place(String item, long cents) {
        notifier.send(item + ": " + payments.charge(cents));
    }
}

@Component
class PlaceAnOrder implements CommandLineRunner {
    private final OrderService orders;

    PlaceAnOrder(OrderService orders) {
        this.orders = orders;
    }

    @Override
    public void run(String... args) {
        orders.place("Keyboard", 4999);
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
email: Keyboard: charged 4999 cents to the card
What’s happening
  1. By hand (left): OrderService doesn't create its collaborators; it receives a PaymentGateway and a Notifier in its constructor and keeps them in final fields. That's already dependency injection. It depends on interfaces, so a test can pass a fake gateway without changing OrderService.
  2. main is the wiring: it decides which implementations exist and calls new for each, inner ones first. It prints email: Keyboard: charged 4999 cents to the card. The weak spot is main itself: with hundreds of classes it's long, order-sensitive, and changes every time a constructor does.
  3. With Spring (right): the classes are the same plus annotations. @Component (and @Service, the same thing with a more specific name) says "Spring, create one of these and manage it". A managed object is a bean.
  4. There's no new anywhere. At startup Spring finds the four annotated classes, sees that OrderService's constructor needs a PaymentGateway and a Notifier, finds the one bean of each type (CardGateway, EmailNotifier), and creates those first.
  5. PlaceAnOrder implements CommandLineRunner, so Spring Boot calls its run method once everything is created: the Spring version of "the code at the bottom of main". The starter's ShopApplication (unchanged) is what starts Spring.
  6. Same output, email: Keyboard: charged 4999 cents to the card. What changed is who decides the wiring: swapping EmailNotifier for an SmsNotifier is now a change to which class is a bean, not to any constructor call.

#Beans, the application context and component scanning

Added

The container is called the application context. Think of it as a registry: a map from bean names and types to the single object Spring created for each. When a constructor asks for a PaymentGateway, Spring looks in the context for a bean of that type.

Beans get into the context in two ways: Spring finds classes annotated with @Component (or one of its specialisations), or you declare them with @Bean methods (next topic). Finding them is component scanning: @SpringBootApplication on ShopApplication switches it on for the class's own package, com.example.shop, and every package below it. Nothing outside that tree is scanned.

The four stereotype annotations all make a bean; the names document the role, and two add behaviour:

AnnotationUse it forExtra behaviour
@Componentanythingnone
@Servicebusiness logicnone (it's documentation)
@Repositorydata accesstranslates database exceptions into Spring's DataAccessException
@Controller / @RestControllerweb endpointshandles HTTP requests (chapter 13)
src/main/java/com/example/shop/Beans.java
package com.example.shop;

import java.util.Arrays;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

@Repository
class ProductRepository {
}

@Service
class CatalogService {
    CatalogService(ProductRepository products) {
    }
}

@Component
class ListMyBeans implements CommandLineRunner {
    private final ApplicationContext context;

    ListMyBeans(ApplicationContext context) {
        this.context = context;
    }

    @Override
    public void run(String... args) {
        String[] mine = Arrays.stream(context.getBeanDefinitionNames())
                .filter(name -> context.getType(name).getPackageName().equals("com.example.shop"))
                .sorted()
                .toArray(String[]::new);
        System.out.println("my beans: " + String.join(", ", mine));
        System.out.println("all beans: more than 100? " + (context.getBeanDefinitionCount() > 100));
        System.out.println("same object every time? " + (context.getBean(CatalogService.class) == context.getBean(CatalogService.class)));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
my beans: catalogService, listMyBeans, productRepository, shopApplication
all beans: more than 100? true
same object every time? true
What’s happening
  1. Spring can inject the ApplicationContext itself, which lets this runner look inside the container. (Real code rarely needs that; it's for seeing what's there.)
  2. getBeanDefinitionNames() lists every bean. Filtering to classes in com.example.shop leaves yours, named after the class with a lower-case first letter: catalogService, listMyBeans, productRepository, and shopApplication (the main class is a bean too).
  3. The context holds far more than your four: more than 100 beans in this app, created by Spring Boot's auto-configuration for the data source, JPA, Jackson, validation and the rest. That's what "Boot configures things for you" means concretely.
  4. Asking twice for CatalogService returns the same object: beans are singletons by default, one per context. That's why beans must be careful with state (Bean scopes and lifecycle).
AdvancedWhen a bean isn't found

The most common Spring startup failure is a dependency nobody provides. Here CardGateway sits in com.example.billing, outside the scanned tree:

src/main/java/com/example/billing/CardGateway.java
package com.example.billing;

import org.springframework.stereotype.Component;

@Component
public class CardGateway implements com.example.shop.PaymentGateway {
    public String charge(long cents) {
        return "charged " + cents;
    }
}
src/main/java/com/example/shop/PaymentGateway.java
package com.example.shop;

public interface PaymentGateway {
    String charge(long cents);
}
src/main/java/com/example/shop/OrderService.java
package com.example.shop;

import org.springframework.stereotype.Service;

@Service
class OrderService {
    OrderService(PaymentGateway payments) {
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
2026-11-26T15:10:54.621Z  WARN 83188 --- [shop] [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'orderService' defined in file [<project>/target/classes/com/example/shop/OrderService.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type 'com.example.shop.PaymentGateway' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
2026-11-26T15:10:54.697Z ERROR 83188 --- [shop] [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.example.shop.OrderService required a bean of type 'com.example.shop.PaymentGateway' that could not be found.


Action:

Consider defining a bean of type 'com.example.shop.PaymentGateway' in your configuration.

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:4.2.0:run (default-cli) on project shop: Process terminated with exit code: 1 -> [Help 1]
What’s happening
  1. CardGateway is a @Component, but in package com.example.billing, which is a sibling of com.example.shop, not below it. Component scanning never sees it, so it's not a bean.
  2. OrderService needs a PaymentGateway, and the context has none. Spring stops creating beans and the app doesn't start. The first log line is the raw exception: UnsatisfiedDependencyException … No qualifying bean of type 'com.example.shop.PaymentGateway' available.
  3. Then Spring Boot's failure analyzer prints the readable version: APPLICATION FAILED TO START, Parameter 0 of constructor in com.example.shop.OrderService required a bean of type 'com.example.shop.PaymentGateway' that could not be found, and a suggested action.
  4. The fixes: move the class under com.example.shop (the usual answer), or widen the scan with @SpringBootApplication(scanBasePackages = "com.example"), or declare the bean with @Bean in a configuration class.
  5. Maven then reports that the app's process exited with code 1. A failing context fails fast at startup, not at the first request, which is a real advantage over discovering a missing dependency in production traffic.

#Constructor injection, @Configuration and @Bean

Added

Spring can inject in three places: the constructor, a setter, or straight into a field with @Autowired. Modern Spring code uses the constructor, and you should too:

  • the dependencies are final, so the object is complete and immutable from the moment it exists;
  • the class is plain Java: a unit test calls new OrderService(fakeGateway, fakeNotifier) with no Spring at all;
  • a missing dependency fails at startup, and a constructor with eight parameters is an honest sign the class does too much.

With a single constructor you don't even need @Autowired: Spring uses it automatically. Field injection (@Autowired private PaymentGateway payments;) still fills old codebases; it hides dependencies and makes tests need Spring or reflection.

Injection is by type. That raises the obvious question: what if there are two beans of the type you ask for?

src/main/java/com/example/shop/Notifiers.java
package com.example.shop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

interface Notifier {
    String send(String message);
}

@Component
class EmailNotifier implements Notifier {
    public String send(String message) {
        return "email: " + message;
    }
}

@Component
class SmsNotifier implements Notifier {
    public String send(String message) {
        return "sms: " + message;
    }
}

@Component
class Welcome implements CommandLineRunner {
    private final Notifier notifier;

    Welcome(Notifier notifier) {
        this.notifier = notifier;
    }

    @Override
    public void run(String... args) {
        System.out.println(notifier.send("welcome, Rohit"));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
2026-11-26T15:10:55.093Z  WARN 83194 --- [shop] [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'welcome' defined in file [<project>/target/classes/com/example/shop/Welcome.class]: Unsatisfied dependency expressed through constructor parameter 0: No qualifying bean of type 'com.example.shop.Notifier' available: expected single matching bean but found 2: emailNotifier,smsNotifier
2026-11-26T15:10:55.192Z ERROR 83194 --- [shop] [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.example.shop.Welcome required a single bean, but 2 were found:
	- emailNotifier: defined in file [<project>/target/classes/com/example/shop/EmailNotifier.class]
	- smsNotifier: defined in file [<project>/target/classes/com/example/shop/SmsNotifier.class]

This may be due to missing parameter name information

Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

Ensure that your compiler is configured to use the '-parameters' flag.
You may need to update both your build tool settings as well as your IDE.
(See https://github.com/spring-projects/spring-framework/wiki/Spring-Framework-6.1-Release-Notes#parameter-name-retention)


[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:4.2.0:run (default-cli) on project shop: Process terminated with exit code: 1 -> [Help 1]
What’s happening
  1. Two beans implement Notifier: emailNotifier and smsNotifier. Welcome's constructor asks for "a Notifier".
  2. Spring refuses to guess: Parameter 0 of constructor in com.example.shop.Welcome required a single bean, but 2 were found, listing both and where each was defined.
  3. It adds a hint about the -parameters compiler flag. Since Spring 6.1, Spring can also pick a bean by the parameter's name (a parameter called smsNotifier would select that bean), which needs parameter names kept in the class file. The starter's parent pom already compiles with -parameters, so here the real cause is just that the parameter is called notifier, which matches neither bean.
  4. The suggested actions are the three real fixes: mark one @Primary (the default when nothing more specific is asked for), put @Qualifier("smsNotifier") on the constructor parameter to pick one by name, or inject all of them with List<Notifier> when you really want both.
  5. This failure is also a design prompt: two implementations of one interface usually means "pick per environment" (use a profile, below) or "use both" (inject the list).
Advanced@Configuration and @Bean: beans you build yourself

@Component works for your own classes. For classes you can't annotate (from the JDK or a library), or when creating the object needs some logic, write a method that returns it, annotate it @Bean, and put it in a @Configuration class. Spring calls the method once and registers the result as a bean.

A good example is time. Code that calls LocalDate.now() directly can't be tested on a fixed date. Code that asks for a java.time.Clock bean can:

src/main/java/com/example/shop/TimeConfig.java
package com.example.shop;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Configuration
class TimeConfig {
    @Bean
    Clock clock() {
        return Clock.fixed(Instant.parse("2026-12-24T10:00:00Z"), ZoneId.of("America/Toronto"));
    }
}

interface Notifier {
    String send(String message);
}

@Component
@Primary
class EmailNotifier implements Notifier {
    public String send(String message) {
        return "email: " + message;
    }
}

@Component
class SmsNotifier implements Notifier {
    public String send(String message) {
        return "sms: " + message;
    }
}

@Component
class DeliveryEstimate implements CommandLineRunner {
    private final Clock clock;
    private final Notifier notifier;

    DeliveryEstimate(Clock clock, Notifier notifier) {
        this.clock = clock;
        this.notifier = notifier;
    }

    @Override
    public void run(String... args) {
        LocalDate arrives = LocalDate.now(clock).plusDays(4);
        System.out.println(notifier.send("your order arrives " + arrives.getDayOfWeek() + " " + arrives));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
email: your order arrives MONDAY 2026-12-28
What’s happening
  1. TimeConfig is a @Configuration class, and its @Bean method returns a Clock frozen at 10:00 UTC on 24 December 2026, in Toronto's time zone. Spring calls clock() once and registers the result as the clock bean.
  2. DeliveryEstimate asks for a Clock and gets that one. LocalDate.now(clock) reads the date from it: 24 December (05:00 in Toronto), plus 4 days is Monday 28 December, printed as MONDAY 2026-12-28.
  3. In production, the @Bean method would return Clock.systemDefaultZone(), and tests would supply a fixed clock. The class under test never changes; only the bean does.
  4. @Primary on EmailNotifier settles the two-candidates problem from the example above: when a constructor just asks for a Notifier, the primary one wins, so the message goes by email:.

#Bean scopes and lifecycle

Added

A bean's scope says how many instances exist. The default, singleton, means one per application context, shared by every class that asks for it and by every request, on many threads at once. That's efficient and almost always what you want for services and repositories, and it has one big consequence: a singleton bean must not keep per-request or per-user state in its fields. It's the same rule as a module-level variable in a Node.js server, which every request shares, except that in Java many threads read and write it at the same time.

ScopeInstancesTypical use
singleton (default)one per contextservices, repositories, clients: stateless or thread-safe
prototypea new one each time it's injected or requesteda stateful helper used by one owner
request / session (web only)one per HTTP request / user sessionrarely needed; prefer passing data as parameters

Beans also have a lifecycle: Spring creates the object, injects its dependencies, calls any method marked @PostConstruct (setup that needs the dependencies, like warming a cache), hands it out, and on shutdown calls @PreDestroy (closing connections). Those annotations come from jakarta.annotation, the Jakarta EE package that replaced javax.annotation.

src/main/java/com/example/shop/Scopes.java
package com.example.shop;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
class VisitCounter {
    private int visits;

    int visit() {
        return ++visits;
    }

    @PostConstruct
    void ready() {
        System.out.println("VisitCounter ready");
    }

    @PreDestroy
    void closing() {
        System.out.println("VisitCounter closing after " + visits + " visits");
    }
}

@Component
@Scope("prototype")
class Basket {
    private int items;

    int add() {
        return ++items;
    }
}

@Component
class HomePage {
    final VisitCounter counter;
    final Basket basket;

    HomePage(VisitCounter counter, Basket basket) {
        this.counter = counter;
        this.basket = basket;
    }
}

@Component
class ProductPage {
    final VisitCounter counter;
    final Basket basket;

    ProductPage(VisitCounter counter, Basket basket) {
        this.counter = counter;
        this.basket = basket;
    }
}

@Component
class ScopeDemo implements CommandLineRunner {
    private final HomePage home;
    private final ProductPage product;

    ScopeDemo(HomePage home, ProductPage product) {
        this.home = home;
        this.product = product;
    }

    @Override
    public void run(String... args) {
        System.out.println("home visit #" + home.counter.visit());
        System.out.println("product visit #" + product.counter.visit());
        System.out.println("same counter? " + (home.counter == product.counter));
        System.out.println("home basket items: " + home.basket.add() + ", product basket items: " + product.basket.add());
        System.out.println("same basket? " + (home.basket == product.basket));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
VisitCounter ready
home visit #1
product visit #2
same counter? true
home basket items: 1, product basket items: 1
same basket? false
VisitCounter closing after 2 visits
What’s happening
  1. When the context starts, Spring creates VisitCounter, then calls its @PostConstruct method: VisitCounter ready prints before anything else.
  2. HomePage and ProductPage both ask for a VisitCounter. It's a singleton, so they get the same object: the home visit makes it 1, the product visit makes it 2, and same counter? true. That shared field is exactly the state that would be a bug if it were, say, "the current user".
  3. Basket is prototype-scoped, so each page got its own basket: each add() returns 1, and same basket? false.
  4. When the program ends, the context closes and calls @PreDestroy on the singletons: VisitCounter closing after 2 visits. (Spring doesn't call @PreDestroy on prototype beans: once it hands one out, it forgets it.)
AdvancedGotcha: prototypes inside singletons

#Configuration, profiles and @ConfigurationProperties

Added

Settings that change between environments (URLs, credentials, limits, feature switches) don't belong in code. Spring Boot reads them from a stack of property sources, and a higher one wins when two set the same key. The ones you'll use, from lowest to highest:

  1. application.properties (or application.yml) inside the JAR: the defaults;
  2. application-<profile>.properties for each active profile (dev, prod);
  3. environment variables: SHOP_CURRENCY sets shop.currency (upper case, dots and dashes become underscores), the usual way in containers;
  4. command-line arguments: --shop.currency=USD.

It's process.env plus dotenv plus per-environment config files, merged into one view with a clear order. The best way to read a group of settings is @ConfigurationProperties on a record: Spring binds every shop.* key to a typed field, converts types, and can validate them at startup.

src/main/java/com/example/shop/ShopProperties.java
package com.example.shop;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("shop")
record ShopProperties(String currency, int freeShippingOver, boolean giftWrap) {
}
src/main/java/com/example/shop/ShowConfig.java
package com.example.shop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@EnableConfigurationProperties(ShopProperties.class)
class ShowConfig implements CommandLineRunner {
    private final ShopProperties shop;

    ShowConfig(ShopProperties shop) {
        this.shop = shop;
    }

    @Override
    public void run(String... args) {
        System.out.println(shop);
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn

shop.currency=CAD
shop.free-shipping-over=50
shop.gift-wrap=false
src/main/resources/application-dev.properties
shop.free-shipping-over=0
shop.gift-wrap=true
Terminal
$ ./mvnw -q spring-boot:run
ShopProperties[currency=CAD, freeShippingOver=50, giftWrap=false]
$ SHOP_CURRENCY=USD ./mvnw -q spring-boot:run
ShopProperties[currency=USD, freeShippingOver=50, giftWrap=false]
$ ./mvnw -q spring-boot:run -Dspring-boot.run.profiles=dev
ShopProperties[currency=CAD, freeShippingOver=0, giftWrap=true]
$ ./mvnw -q spring-boot:run -Dspring-boot.run.profiles=dev -Dspring-boot.run.arguments=--shop.currency=EUR
ShopProperties[currency=EUR, freeShippingOver=0, giftWrap=true]
What’s happening
  1. ShopProperties is a record bound to the shop prefix. Boot's relaxed binding maps shop.free-shipping-over (kebab case, the recommended style in files) to the component freeShippingOver, and converts "50" to an int and "false" to a boolean. @EnableConfigurationProperties registers it as a bean.
  2. With only application.properties, it prints ShopProperties[currency=CAD, freeShippingOver=50, giftWrap=false].
  3. SHOP_CURRENCY=USD is an environment variable, which beats the file: currency=USD, the rest unchanged. This is how a container or Kubernetes deployment configures the same JAR differently.
  4. The dev profile (passed through the Maven plugin as -Dspring-boot.run.profiles=dev; with a JAR it's --spring.profiles.active=dev) layers application-dev.properties on top: free shipping from 0 and gift wrap on, currency still CAD.
  5. A command-line argument beats everything: --shop.currency=EUR with the dev profile gives currency=EUR, freeShippingOver=0, giftWrap=true.
AdvancedTip: secrets and validated settings

#Auto-configuration and starters

Added

The starter project has no configuration of its own, yet its context contains a connection pool, a JPA setup, a transaction manager, a JSON mapper and a web server. Auto-configuration made them. Each spring-boot-* module ships configuration classes that define beans conditionally:

  • @ConditionalOnClass: only if a library is on the classpath (H2 or PostgreSQL's driver → configure a DataSource);
  • @ConditionalOnMissingBean: only if you haven't defined one already;
  • @ConditionalOnProperty: only if a setting says so.

A starter is just a dependency that brings the right libraries, and with them the auto-configuration they trigger. So the mental model is: adding a starter turns features on, and defining your own bean makes Boot's default step aside. Boot 4 split this into smaller modules (one per technology, each with a starter and a -test starter), so an app only carries the auto-configuration it uses.

src/main/java/com/example/shop/WhatBootMade.java
package com.example.shop;

import javax.sql.DataSource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import tools.jackson.databind.json.JsonMapper;

@Component
class WhatBootMade implements CommandLineRunner {
    private final DataSource dataSource;
    private final PlatformTransactionManager transactions;
    private final JsonMapper json;

    WhatBootMade(DataSource dataSource, PlatformTransactionManager transactions, JsonMapper json) {
        this.dataSource = dataSource;
        this.transactions = transactions;
        this.json = json;
    }

    @Override
    public void run(String... args) {
        System.out.println("DataSource: " + dataSource.getClass().getSimpleName());
        System.out.println("Transactions: " + transactions.getClass().getSimpleName());
        System.out.println("JSON: " + json.writeValueAsString(new Price("Mouse", 1950)));
    }

    record Price(String name, long cents) {
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
DataSource: HikariDataSource
Transactions: JpaTransactionManager
JSON: {"name":"Mouse","cents":1950}
$ ./mvnw -q spring-boot:run -Dspring-boot.run.arguments=--debug | grep -A3 "DataSourceAutoConfiguration matched"
   DataSourceAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType' (OnClassCondition)
      - @ConditionalOnMissingBean (types: io.r2dbc.spi.ConnectionFactory; SearchStrategy: all) did not find any beans (OnBeanCondition)
What’s happening
  1. This class asks for three beans you never defined. All three exist, made by auto-configuration from the starters in the pom.
  2. HikariDataSource: the JDBC starter found H2 on the classpath and no DataSource bean of yours, so it created a HikariCP connection pool for an in-memory H2 database. JpaTransactionManager came from the JPA starter.
  3. JsonMapper is Jackson 3's mapper (package tools.jackson, where Jackson 2 was com.fasterxml.jackson), configured by Boot; it turns the record into {"name":"Mouse","cents":1950}, keys in the record's component order. You never wrote a line of JSON code, and chapter 13's controllers use this same mapper for every response.
  4. --debug prints the conditions evaluation report: for every auto-configuration, whether it matched and why. DataSourceAutoConfiguration matched because the required classes (javax.sql.DataSource and Spring's embedded database support) were found, and no R2DBC ConnectionFactory bean existed.
  5. When something "isn't being configured" (or is, unexpectedly), that report is the first place to look. It's long; search it for the auto-configuration's name.
AdvancedYour own bean wins
src/main/java/com/example/shop/MyDataSource.java
package com.example.shop;

import javax.sql.DataSource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component;

@Configuration
class MyDataSource {
    @Bean
    DataSource dataSource() {
        return new DriverManagerDataSource("jdbc:h2:mem:mine", "sa", "");
    }
}

@Component
class Check implements CommandLineRunner {
    private final DataSource dataSource;

    Check(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public void run(String... args) {
        System.out.println("DataSource: " + dataSource.getClass().getSimpleName());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
DataSource: DriverManagerDataSource
What’s happening
  1. This app defines its own DataSource bean: a simple DriverManagerDataSource (no pool) for an H2 database called mine.
  2. Boot's data source auto-configuration is @ConditionalOnMissingBean(DataSource.class), so it backs off: no Hikari pool is created, and JPA uses your data source instead.
  3. It prints DataSource: DriverManagerDataSource. Overriding a Boot default is just "define the bean yourself", with no special API. (In a real app you'd usually keep Hikari and tune it with spring.datasource.hikari.* properties instead.)

#Proxies and AOP

Added

Annotations like @Transactional, @Cacheable, @Async and @PreAuthorize add behaviour around your method: start a transaction, check a cache, run on another thread, check a permission. Spring doesn't change your class's code to do it. It wraps the bean in a proxy: a generated subclass that intercepts each call, does the extra work, and then calls your real method. That's aspect-oriented programming (AOP), and the proxy is what other beans actually receive when they inject yours.

The mental model is a receptionist in front of an office. Calls from outside go through the receptionist, who can open the transaction first. But a call from inside the office, one method of the bean calling another method of the same bean through this, never passes the receptionist. That's the famous self-invocation trap, and interviewers love it.

src/main/java/com/example/shop/Proxies.java
package com.example.shop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Service
class OrderService {
    @Transactional
    public String placeOrder() {
        return "placeOrder in a transaction? " + TransactionSynchronizationManager.isActualTransactionActive();
    }

    public String placeOrderLater() {
        return "via this: " + placeOrder();
    }
}

@Component
class ProxyDemo implements CommandLineRunner {
    private final OrderService orders;

    ProxyDemo(OrderService orders) {
        this.orders = orders;
    }

    @Override
    public void run(String... args) {
        System.out.println("injected class: " + orders.getClass().getSimpleName());
        System.out.println(orders.placeOrder());
        System.out.println(orders.placeOrderLater());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
injected class: OrderService$$SpringCGLIB$$0
placeOrder in a transaction? true
via this: placeOrder in a transaction? false
What’s happening
  1. OrderService has a @Transactional method, so Spring doesn't inject the plain object: it injects a subclass generated at startup with CGLIB, OrderService$$SpringCGLIB$$0. That's the proxy.
  2. orders.placeOrder() goes through the proxy, which starts a transaction before calling the real method: isActualTransactionActive() is true.
  3. orders.placeOrderLater() isn't transactional, so the proxy just passes it on. Inside, it calls placeOrder() on this, the real object, which skips the proxy. No transaction starts: via this: placeOrder in a transaction? false.
  4. The annotation is still there, but it does nothing on that path. In real code that means writes you thought were atomic aren't, and no error tells you.
  5. Fixes: call the method through the proxy, which in practice means moving it to another bean and injecting that; or make the outer method transactional instead. The same applies to @Cacheable, @Async and @PreAuthorize.
AdvancedGotcha: what a proxy can't intercept

#What happens when a Spring Boot app starts

Added

Reading a startup log is a daily skill: it tells you which profile is active, which port the server took, whether the database connected and how long startup took. The sequence behind it:

  1. main calls SpringApplication.run(ShopApplication.class, args).
  2. Boot prepares the environment: property sources and active profiles.
  3. It creates the application context, scans for components and loads auto-configurations, evaluating their conditions.
  4. It creates the singleton beans in dependency order: the connection pool, JPA, Jackson, then your services.
  5. For a web app, it starts the embedded Tomcat on port 8080: the server is a library inside your app, not something you deploy into.
  6. It runs CommandLineRunner / ApplicationRunner beans and logs Started … in N seconds. The app is now serving requests.
src/main/java/com/example/shop/ShopApplication.java
package com.example.shop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ShopApplication {

	public static void main(String[] args) {
		SpringApplication.run(ShopApplication.class, args);
	}

}
Terminal
$ ./mvnw -q -DskipTests package
$ java -jar target/shop-0.0.1-SNAPSHOT.jar &
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v4.2.0)

2026-11-26T15:12:06.471Z  INFO 85231 --- [shop] [           main] com.example.shop.ShopApplication         : Starting ShopApplication v0.0.1-SNAPSHOT using Java 25.0.5.1 with PID 85231 (<project>/target/shop-0.0.1-SNAPSHOT.jar started by <user> in <project>)
2026-11-26T15:12:06.477Z  INFO 85231 --- [shop] [           main] com.example.shop.ShopApplication         : No active profile set, falling back to 1 default profile: "default"
2026-11-26T15:12:09.447Z  INFO 85231 --- [shop] [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2026-11-26T15:12:09.667Z  INFO 85231 --- [shop] [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 208 ms. Found 0 JPA repository interfaces.
2026-11-26T15:12:11.452Z  INFO 85231 --- [shop] [           main] o.s.boot.tomcat.TomcatWebServer          : Tomcat initialized with port 8080 (http)
2026-11-26T15:12:11.522Z  INFO 85231 --- [shop] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2026-11-26T15:12:11.524Z  INFO 85231 --- [shop] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/11.0.27]
2026-11-26T15:12:11.574Z  INFO 85231 --- [shop] [           main] b.w.c.s.WebApplicationContextInitializer : Root WebApplicationContext: initialization completed in 5028 ms
2026-11-26T15:12:12.399Z  INFO 85231 --- [shop] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2026-11-26T15:12:13.000Z  INFO 85231 --- [shop] [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:a80b0dcf-c66b-430e-a59b-9c16135b1b6a user=SA
2026-11-26T15:12:13.001Z  INFO 85231 --- [shop] [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2026-11-26T15:12:13.035Z  INFO 85231 --- [shop] [           main] org.hibernate.orm.jpa                    : HHH008540: Processing PersistenceUnitInfo [name: default]
2026-11-26T15:12:13.133Z  INFO 85231 --- [shop] [           main] org.hibernate.orm.core                   : HHH000001: Hibernate ORM core version 7.4.15.Final
2026-11-26T15:12:13.933Z  INFO 85231 --- [shop] [           main] o.s.o.j.p.SpringPersistenceUnitInfo      : No LoadTimeWeaver setup: ignoring JPA class transformer
2026-11-26T15:12:14.055Z  INFO 85231 --- [shop] [           main] org.hibernate.orm.connections.pooling    : HHH10001005: Database info:
	Database JDBC URL [jdbc:h2:mem:a80b0dcf-c66b-430e-a59b-9c16135b1b6a]
	Database driver: H2 JDBC Driver
	Database dialect: H2Dialect
	Database version: 2.5.252
	Default catalog/schema: A80B0DCF-C66B-430E-A59B-9C16135B1B6A/PUBLIC
	Autocommit mode: undefined/unknown
	Isolation level: READ_COMMITTED [default READ_COMMITTED]
	JDBC fetch size: 100
	Pool: DataSourceConnectionProvider
	Minimum pool size: undefined/unknown
	Maximum pool size: undefined/unknown
2026-11-26T15:12:14.685Z  INFO 85231 --- [shop] [           main] org.hibernate.orm.core                   : HHH000489: No JTA platform available (set 'hibernate.transaction.jta.platform' to enable JTA platform integration)
2026-11-26T15:12:14.746Z  INFO 85231 --- [shop] [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2026-11-26T15:12:14.915Z  WARN 85231 --- [shop] [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2026-11-26T15:12:16.499Z  INFO 85231 --- [shop] [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint beneath base path '/actuator'
2026-11-26T15:12:16.607Z  INFO 85231 --- [shop] [           main] o.s.boot.tomcat.TomcatWebServer          : Tomcat started on port 8080 (http) with context path '/'
2026-11-26T15:12:16.697Z  INFO 85231 --- [shop] [           main] com.example.shop.ShopApplication         : Started ShopApplication in 10.808 seconds (process running for 11.432)
$ curl -s localhost:8080/actuator/health
{"groups":["liveness","readiness"],"status":"UP"}
What’s happening
  1. This is the starter, unchanged, with its default logging. java -jar … & starts it in the background; the log is what it printed up to the "Started" line.
  2. The banner, then Starting ShopApplication v0.0.1-SNAPSHOT using Java 25.0.5.1 with PID …, then No active profile set, falling back to 1 default profile: "default": step 2, the environment.
  3. Bootstrapping Spring Data JPA repositories … Found 0 JPA repository interfaces: component scanning found no repositories yet (chapter 14 adds some). Tomcat initialized with port 8080 and Starting Servlet engine: [Apache Tomcat/11.0.27]: the embedded server is being set up.
  4. HikariPool-1 - Start completed, Hibernate's version and the database info (an in-memory H2 2.5.252 database with a random name): the data source and JPA beans being created.
  5. The WARN line about spring.jpa.open-in-view is Boot telling you a default is risky; chapter 14 explains it and switches it off. Exposing 1 endpoint beneath base path '/actuator' is Actuator (only health is exposed by default).
  6. Tomcat started on port 8080 (http) and Started ShopApplication in … seconds: ready. The curl gets {"groups":["liveness","readiness"],"status":"UP"}.

#Your turn: Spring core

Added
Your turn: choose the notifier by name

With EmailNotifier and SmsNotifier both beans (as in the two-candidates example), make Welcome use the SMS one without @Primary, so the app prints sms: welcome, Rohit.

Show answer
src/main/java/com/example/shop/Notifiers.java
package com.example.shop;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

interface Notifier {
    String send(String message);
}

@Component
class EmailNotifier implements Notifier {
    public String send(String message) {
        return "email: " + message;
    }
}

@Component
class SmsNotifier implements Notifier {
    public String send(String message) {
        return "sms: " + message;
    }
}

@Component
class Welcome implements CommandLineRunner {
    private final Notifier notifier;

    Welcome(@Qualifier("smsNotifier") Notifier notifier) {
        this.notifier = notifier;
    }

    @Override
    public void run(String... args) {
        System.out.println(notifier.send("welcome, Rohit"));
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
sms: welcome, Rohit
What’s happening
  1. A bean's default name is its class name with a lower-case first letter, so the SMS bean is smsNotifier.
  2. @Qualifier("smsNotifier") on the constructor parameter narrows "any Notifier" to that one bean, so the ambiguity is gone.
  3. It prints sms: welcome, Rohit. @Qualifier beats @Primary when both are present: a specific request wins over a default.
Your turn: a validated setting

Add a shop.max-items-per-order setting to a @ConfigurationProperties record so that the app refuses to start when it's below 1, and show what happens when someone sets it to 0.

Show answer
src/main/java/com/example/shop/OrderLimits.java
package com.example.shop;

import jakarta.validation.constraints.Min;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

@Validated
@ConfigurationProperties("shop")
record OrderLimits(@Min(1) int maxItemsPerOrder) {
}

@Component
@EnableConfigurationProperties(OrderLimits.class)
class ShowLimits implements CommandLineRunner {
    private final OrderLimits limits;

    ShowLimits(OrderLimits limits) {
        this.limits = limits;
    }

    @Override
    public void run(String... args) {
        System.out.println("max items per order: " + limits.maxItemsPerOrder());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn

shop.max-items-per-order=20
Terminal
$ ./mvnw -q spring-boot:run
max items per order: 20
$ SHOP_MAXITEMSPERORDER=0 ./mvnw -q spring-boot:run
2026-11-26T15:12:41.814Z  WARN 85899 --- [shop] [           main] s.c.a.AnnotationConfigApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'showLimits' defined in file [<project>/target/classes/com/example/shop/ShowLimits.class]: Unsatisfied dependency expressed through constructor parameter 0: Error creating bean with name 'shop-com.example.shop.OrderLimits': Could not bind properties to 'OrderLimits' : prefix=shop, ignoreInvalidFields=false, ignoreUnknownFields=true
2026-11-26T15:12:41.840Z ERROR 85899 --- [shop] [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target com.example.shop.OrderLimits failed:

    Property: shop.maxItemsPerOrder
    Value: "0"
    Origin: System Environment Property "SHOP_MAXITEMSPERORDER"
    Reason: must be greater than or equal to 1


Action:

Update your application's configuration

[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:4.2.0:run (default-cli) on project shop: Process terminated with exit code: 1 -> [Help 1]
What’s happening
  1. @Validated on the properties record makes Boot run Bean Validation when it binds the settings (the starter includes the validation starter). @Min(1) is the rule.
  2. With the file's value, 20, the app starts and prints max items per order: 20.
  3. The environment variable SHOP_MAXITEMSPERORDER=0 overrides it (for environment variables, relaxed binding drops the dashes). Binding fails validation, and the failure analyzer reports which property, which value and which rule: the app never starts.
  4. A bad deployment setting is caught in the first second, by the deployment itself, instead of by a customer.
Your turn: fix the self-invocation

In the proxy example, placeOrderLater() calls placeOrder() through this, so no transaction starts. Restructure the code so that the later order does run in a transaction, keeping placeOrder @Transactional.

Show answer
src/main/java/com/example/shop/Proxies.java
package com.example.shop;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;

@Service
class OrderService {
    @Transactional
    public String placeOrder() {
        return "placeOrder in a transaction? " + TransactionSynchronizationManager.isActualTransactionActive();
    }
}

@Service
class LaterOrders {
    private final OrderService orders;

    LaterOrders(OrderService orders) {
        this.orders = orders;
    }

    public String placeOrderLater() {
        return "via the proxy: " + orders.placeOrder();
    }
}

@Component
class ProxyDemo implements CommandLineRunner {
    private final LaterOrders later;

    ProxyDemo(LaterOrders later) {
        this.later = later;
    }

    @Override
    public void run(String... args) {
        System.out.println(later.placeOrderLater());
    }
}
src/main/resources/application.properties
spring.application.name=shop
spring.main.web-application-type=none
spring.main.banner-mode=off
logging.level.root=warn
Terminal
$ ./mvnw -q spring-boot:run
via the proxy: placeOrder in a transaction? true
What’s happening
  1. placeOrderLater moved to a separate bean, LaterOrders, which gets OrderService injected, and what's injected is the proxy.
  2. orders.placeOrder() now goes through the proxy, which starts the transaction: via the proxy: placeOrder in a transaction? true.
  3. This is the standard fix, and often a better design anyway: "place an order later" is a different responsibility from "place an order".

Written fresh, no doc. Examples were run with Eclipse Temurin 25.0.5.1 and Spring Boot 4.2.0 (Maven 3.10.1); facts come from openjdk.org, docs.oracle.com and spring.io, read 2026-11-26.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.