TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท java ยท frameworks ยท backend

Spring and Spring Boot

A framework that creates your application's objects, wires them together and wraps them with features like web endpoints and transactions, so your own code can stick to the business logic.

15 min5 animations

๐Ÿ–จ๏ธ Cheat sheet

A restaurant that runs itself

Picture a small cafรฉ where every cook hires their own helpers. The sauce cook goes looking for someone to chop vegetables, the vegetable chopper goes looking for a supplier, and nobody is quite sure who works with whom.

A big restaurant works differently. A manager hires everyone and introduces them: "You make the sauce. Your vegetables come from Sam." The cooks never hire anyone. They just say what they need, and the manager makes sure they have it.

Spring is that manager. Every worker it hires is called a bean.

Inversion of control

At the heart of Spring is the ApplicationContext, also called the container. At startup it:

  1. Scans your packages for classes marked @Component or one of its specialisations: @Service, @Repository, @RestController, @Configuration.
  2. Works out the dependency graph from their constructors.
  3. Creates the beans in dependency order and injects each one into the beans that need it.

Your classes never call new on their collaborators; the container does. That reversal is called inversion of control, and handing in the dependencies is dependency injection.

TermMeaning
BeanAn object created and managed by the container
ApplicationContextThe container: holds the beans and their configuration
Singleton scopeThe default: one shared instance of each bean
Component scanningFinding bean classes by their annotations
The container builds and wires your beans5 steps
๐Ÿฝ๏ธ The restaurant (run by the manager)๐Ÿ“‹ List of jobs
Press play and watch it happen!

Ask, don't fetch

The cashier needs someone to take card payments, but doesn't care who, as long as they can charge a card. On a normal day the manager hands over the real card machine. On practice day the manager hands over a pretend one, and the cashier works exactly the same way.

Because the cashier only asks for "something that can charge a card", the manager can swap what it gets.

Dependency injection and interfaces

Ask for dependencies in the constructor, and depend on interfaces rather than concrete classes:

1@Service2public class CheckoutService {3    private final PaymentGateway gateway;4 5    public CheckoutService(PaymentGateway gateway) { // Spring passes the bean in6        this.gateway = gateway;7    }8 9    public Receipt checkout(Cart cart) {10        return gateway.charge(cart.total());11    }12}

Which PaymentGateway arrives is decided by configuration, not by CheckoutService. Mark implementations with @Profile("prod") and @Profile("test"), or replace a bean in a test with @MockitoBean. Constructor injection also makes dependencies explicit, lets fields be final, and lets you build the class by hand in a plain unit test.

Swapping a dependency5 steps
โ˜€๏ธ Normal day๐Ÿง‘โ€๐Ÿ’ผCashier๐Ÿ’ณReal card machine๐Ÿฆ Bank
Press play and watch it happen!

Taking an order

When a customer asks for something, a head waiter at the door takes the request and passes it to the right station. The waiter there asks the cook, the cook asks the pantry keeper, and the answer travels back up the line. Finally the head waiter writes it on a card the customer can read.

Spring MVC

A Spring Boot web app runs an embedded Tomcat server that hands every request to the DispatcherServlet. It picks the controller method whose mapping matches, converts path variables, query parameters and JSON bodies into Java arguments, calls it, and converts the return value back into JSON with Jackson.

1@RestController2@RequestMapping("/orders")3class OrderController {4    private final OrderService orders;5 6    OrderController(OrderService orders) {7        this.orders = orders;8    }9 10    @GetMapping("/{id}")11    Order get(@PathVariable long id) {12        return orders.find(id);13    }14}

Controllers stay thin: they translate HTTP into method calls. The logic lives in services, and data access in repositories.

A web request through Spring MVC6 steps
๐Ÿฝ๏ธ The restaurant๐Ÿง’Customer๐ŸคตHead waiter๐Ÿ™‹Orders station๐Ÿง‘โ€๐ŸณCook๐ŸงบPantry keeper๐Ÿฌ Storeroom
Press play and watch it happen!

The invisible assistant

Some cooks have an assistant standing in front of them. Before each order the assistant opens a fresh page in the order book. If the cook finishes, the assistant signs the page and it all counts. If the cook drops a plate halfway, the assistant tears out the page, as if the order never happened.

The waiter doesn't even know the assistant is there.

Proxies and @Transactional

For beans that use features such as @Transactional, @Cacheable or @Async, Spring injects a proxy: an object with the same type that wraps the real bean. The proxy adds behaviour around each call. For @Transactional it begins a transaction, calls your method, then commits, or rolls back if the method throws a RuntimeException.

1@Transactional2public void placeOrder(Order order) {3    orders.insert(order);4    stock.decrement(order.items()); // throws? both changes are rolled back5}

The classic trap: calling a @Transactional method from another method of the same class skips the proxy, so no transaction starts. Checked exceptions don't trigger a rollback unless you ask with rollbackFor.

@Transactional works through a proxy6 steps
๐ŸคตWaiter๐Ÿง‘โ€๐Ÿ’ผAssistant๐Ÿง‘โ€๐ŸณCook๐Ÿ“– Order book
Press play and watch it happen!

A ready-made kitchen

With Spring Boot you don't set up the kitchen yourself. You bring boxes of gear, a stove kit and a fridge kit, and a setup crew installs whatever is in the boxes with sensible settings. If you bring your own fridge, the crew leaves theirs in the box.

Spring Boot auto-configuration

Starters such as spring-boot-starter-webmvc or spring-boot-starter-jdbc bring a set of libraries onto the classpath. Auto-configuration then creates the beans those libraries need, guarded by conditions:

ConditionMeaning
@ConditionalOnClassOnly if a library is on the classpath
@ConditionalOnPropertyOnly if a setting is present, or has a given value
@ConditionalOnMissingBeanOnly if you haven't defined one yourself

Settings come from application.yaml, environment variables and profiles. Because of @ConditionalOnMissingBean, any bean you declare replaces Boot's default. Run with --debug to see the condition report: which auto-configurations applied and why.

๐Ÿ”ง Going deeper

Other scopes: besides singletons, beans can be prototype (new instance per injection) or web-scoped (request, session). A singleton holding request-specific state in fields is a common source of bugs, because every request shares it.

Circular dependencies: if A needs B and B needs A through their constructors, startup fails. It usually means one of them is doing two jobs, so split it.

Startup cost: classpath scanning and reflection take time. Spring Boot can also compile ahead of time to a native image with GraalVM, trading build time for very fast startup.

Spring Boot sets things up for you5 steps
๐Ÿณ Your kitchen๐Ÿ“ฆ Boxes of gear๐Ÿ‘ทSetup crew
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 3 questions about Spring and Spring Boot, told the same way as the story.
  1. In a big restaurant, who hires the staff and introduces them?
  2. On practice day the cashier gets a pretend card machine. Why does the cashier work the same way?
  3. The cook drops a plate halfway through an order. What does the invisible assistant do?
Answer every question to check.Passing marks Spring and Spring Boot as done.
Got the hang of Spring and Spring Boot? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ—ƒ๏ธ Spring and databasesStep 1 of 7

Next on the path โ†’๐Ÿ›’ Transactions and isolation

๐Ÿ‘‰ Read next

  • ๐Ÿ›’Transactions and isolationPaying at a till, where money leaves your purse and enters the till together or not at all.
  • ๐Ÿ“Spring transactions (@Transactional)A notary's clerk who opens a contract folder before the work and seals or shreds it at the end.