10 · Spring and Spring Boot / LESSON 46 OF 102
Beans, injection, and layers
Separate HTTP concerns from business behavior.
Before this lesson: Generate and run Spring Boot
Understand the topic
A bean is a Spring-managed object. @Service registers a business collaborator through scanning. A single constructor receives dependencies without requiring @Autowired. Missing or ambiguous dependencies fail startup.
Use controller → service → repository boundaries. Default singleton services are shared across requests, so keep them stateless. Do not store the current user or request data in instance fields.
EXAMPLE · JAVA
src/main/java/com/example/tasks/TitleService.java
package com.example.tasks;
import org.springframework.stereotype.Service;
@Service
public class TitleService {
public String normalize(String title) {
if (title == null || title.isBlank())
throw new IllegalArgumentException("Title required");
return title.strip();
}
}What to expect
A TitleService bean is available for injection; it is not an HTTP endpoint.
YOUR TURN
Put it into practice
- 01Construct TitleService in a plain unit test.
- 02Explain why it has no mutable fields.
- 03Draw and describe the three layers.
Pass a quiz or complete a lab to check today’s streak. Each lesson counts once per day, including when you review it later.
UNDER THE HOOD
Build the mental model
The container assembles an object graph. Constructor dependencies express the graph explicitly.
- 01A single constructor is an unambiguous injection point. Multiple candidates for an interface need an intentional choice such as a qualifier.
- 02Singleton is the default scope, so one instance may serve many threads. Store request data in method arguments, not bean fields.
- 03Proxy-based features such as transactions wrap managed objects. Objects created with new outside the container do not automatically receive those features.
A mistake worth avoiding
Do not use field injection to hide circular dependencies.
DEBUGGING ROOM
Something broke. Where do you look?
Application startup reports two candidate implementations.
Before revealing the diagnosis, write down your first investigation step.
CHECK YOUR UNDERSTANDING
A service stores currentUser in a mutable field. What is the risk?
BUILD IT YOURSELF
Design a replaceable storage boundary
- 1.Define a task-store interface.
- 2.Inject a fake in a unit test and a repository adapter in the app.
- 3.Keep business methods independent of HTTP objects.
Acceptance checklist
Lab completion is your self-report. Knowledge checks do not certify project quality.
RETRIEVE IT FROM MEMORY
What behavior is lost when you construct a proxied service with new?
Revisit this lesson in three days after a successful check or lab.
Ready for the next step?
Explain who creates beans and why constructor injection helps tests.
Reading is separate from passing a knowledge check or completing a lab.