Chapter 2 of 9 · 4 practices · 2 min · 3-question quiz
Structure and dependency injection
How to organise packages and wire beans so the code stays testable and the application context stays easy to reason about.
Start: Use constructor injection with final fields4 practices in this chapter
- 1Use constructor injection with final fieldsField injection with
@Autowiredon a private field looks short, but it hides dependencies, makes fields mutable and forces tests to use reflection or a Spring context to set them. - 2Package by feature, with the application class at the root
@SpringBootApplicationscans its own package and every package below it. Put the main class in the root package (com.example.shop) so components are found without extra@ComponentScan… - 3Keep controllers thin and business logic in servicesA controller's job is HTTP: read the request, validate it, call a service and map the result to a response. When business rules live in controllers, they cannot be reused by a scheduled job or a…
- 4Fix circular dependencies instead of allowing themSpring Boot prohibits circular references by default, and the startup error lists the cycle. It is tempting to set
spring.main.allow-circular-references=trueor add@Lazyto make it go away, but…
Check yourself on this chapter
3 questions, right here once you are signed in. Your progress is saved as you read.