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:
- Scans your packages for classes marked
@Componentor one of its specialisations:@Service,@Repository,@RestController,@Configuration. - Works out the dependency graph from their constructors.
- 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.
| Term | Meaning |
|---|---|
| Bean | An object created and managed by the container |
| ApplicationContext | The container: holds the beans and their configuration |
| Singleton scope | The default: one shared instance of each bean |
| Component scanning | Finding bean classes by their annotations |
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 {3private final PaymentGateway gateway;45public CheckoutService(PaymentGateway gateway) { // Spring passes the bean in6this.gateway = gateway;7}89public Receipt checkout(Cart cart) {10return 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.
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 {4private final OrderService orders;56OrderController(OrderService orders) {7this.orders = orders;8}910@GetMapping("/{id}")11Order get(@PathVariable long id) {12return orders.find(id);13}14}
Controllers stay thin: they translate HTTP into method calls. The logic lives in services, and data access in repositories.
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) {3orders.insert(order);4stock.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.
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:
| Condition | Meaning |
|---|---|
@ConditionalOnClass | Only if a library is on the classpath |
@ConditionalOnProperty | Only if a setting is present, or has a given value |
@ConditionalOnMissingBean | Only 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.
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.