Chapter 15

Best practices and common pitfalls

The previous fourteen chapters, compressed into rules you can put in a code review checklist — plus the fifteen mistakes that account for most Spring Boot incidents.

⏱ 22 min readLevel: allReference

Package by feature, not by layer

Layer packages — avoid

com.bitsnippets.bookstore
├── controller/
│   ├── BookController
│   ├── AuthorController
│   └── ReviewController
├── service/
│   ├── BookService …
├── repository/
└── model/

One feature change touches four folders. Everything must be public. The structure tells you the app uses Spring, and nothing about what it does.

Feature packages — prefer

com.bitsnippets.bookstore
├── catalog/
│   ├── Book, BookRepository
│   ├── BookService, BookController
│   └── dto/
├── author/
├── review/
├── security/
└── common/   error, config, aop

One feature, one folder. Repositories can be package-private. The structure describes the domain — and extracting a service later means moving one folder.

Layering rules

LayerMay doMust never
Controller Map HTTP to a service call, validate input, choose a status code Contain business rules, be @Transactional, touch a repository, return an entity
Service Own business rules and the transaction boundary Know about HTTP — no HttpServletRequest, no ResponseEntity
Repository Query and persist Contain business logic or call other services
Entity Model the database and protect its own invariants Be serialised to a client, or carry Jackson annotations
DTO Model the API contract Have JPA annotations
Enforce it, do not just document it

ArchUnit turns these rules into failing tests instead of review comments.

@AnalyzeClasses(packages = "com.bitsnippets.bookstore")
class ArchitectureTest {

    @ArchTest
    static final ArchRule controllersMustNotTouchRepositories =
            noClasses().that().areAnnotatedWith(RestController.class)
                       .should().dependOnClassesThat()
                       .areAssignableTo(JpaRepository.class);

    @ArchTest
    static final ArchRule transactionsBelongToServices =
            methodsThat().areAnnotatedWith(Transactional.class)
                         .should().beDeclaredInClassesThat()
                         .areAnnotatedWith(Service.class);

    @ArchTest
    static final ArchRule noFieldInjection =
            noFields().should().beAnnotatedWith(Autowired.class);

    @ArchTest
    static final ArchRule noCycles =
            slices().matching("com.bitsnippets.bookstore.(*)..")
                    .should().beFreeOfCycles();
}

Naming conventions

ThingConventionExample
Controller<Aggregate>ControllerBookController
Service<Aggregate>ServiceBookService
Repository<Entity>RepositoryBookRepository
Request DTO<Action><Entity>RequestCreateBookRequest
Response DTO<Entity>ResponseBookResponse
Properties<Feature>PropertiesInventoryProperties
Exception<Problem>ExceptionBookNotFoundException
Config class<Feature>ConfigSecurityConfig
Property keyskebab-case, your own prefixbookstore.max-page-size
URL pathsplural nouns, no verbs/api/books/{id}/reviews
Do not create an interface for every service

BookService plus BookServiceImpl with exactly one implementation adds a file, an indirection and a navigation step for zero benefit. Modern mocking does not need an interface. Extract one when a second implementation genuinely appears.

The fifteen mistakes

1 · Field injection

@Autowired on a field prevents final, hides how many dependencies a class has, makes plain unit tests impossible and lets circular dependencies slip through. Constructor injection, always.

2 · Self-invocation of an annotated method

this.transactionalMethod() bypasses the proxy. No transaction, no async, no caching, no security check, and no warning. Move the method to another bean.

3 · Returning entities from controllers

Couples your API to the schema, leaks fields added later, and triggers lazy loading during serialisation. Use DTOs.

4 · Leaving open-in-view at its default

Holds a database connection for the whole request and hides N+1 queries until the connection pool runs out. Set it to false on day one.

5 · ddl-auto: update in a real environment

Hibernate silently altering production schemas, with no review, no rollback and no ability to drop or rename. Flyway or Liquibase owns the schema.

6 · N+1 queries

A list query plus a lazy association touched per row. Fix with a fetch join or @EntityGraph, and assert query counts in tests so it cannot return.

7 · Catching an exception inside @Transactional

The transaction is already marked rollback-only, so the commit fails with UnexpectedRollbackException. Isolate genuinely recoverable work with REQUIRES_NEW.

8 · Checked exceptions do not roll back

Spring rolls back on RuntimeException and Error only. Make domain exceptions unchecked, or set rollbackFor.

9 · No timeouts on outbound calls

The default is infinite. One slow dependency exhausts the request thread pool and takes the whole service down. Set connect and read timeouts on every client.

10 · Secrets in application.yml

They end up in the jar, the image, the git history and every laptop. Environment variables or a secret manager, always.

11 · Exposing all actuator endpoints

include: "*" publishes /env, /heapdump and /configprops. Separate port, explicit list, role-protected.

12 · anyRequest() placed first in the security rules

First match wins, so every rule after it is dead code. anyRequest() is always last.

13 · Unbounded page sizes

?size=1000000 is a denial-of-service endpoint you built yourself. Cap it with spring.data.web.pageable.max-page-size.

14 · Scheduled jobs on every replica

Three pods means the nightly job runs three times, concurrently. ShedLock, a database advisory lock, or an external scheduler.

15 · A test suite with twenty different contexts

Every unique combination of properties and mocks builds a new ApplicationContext. Standardise on shared base classes and prefer slices.

Performance checklist

CheckWhyChapter
No N+1 on list endpointsThe single biggest latency win available08
Projections instead of full entitiesLess I/O, less garbage08
Connection pool sized to the database, not upward by reflexMore connections than the DB has cores makes things slower08
Timeouts everywherePrevents cascading failure06
Response compression onCheap bandwidth win on JSON06
Caching only where the hit ratio justifies itA cold cache is pure overhead13
Virtual threads for I/O-bound work (Java 21)Removes pool tuning entirely13
Indexes matching your WHERE and ORDER BYThe framework will happily scan forever—
Startup time tracked as a metricCatches accidental heavy work at boot12

Security baseline

  • Deny by default: anyRequest().authenticated() last.
  • HTTPS and HSTS; correct forwarded-header handling behind a proxy.
  • BCrypt 12+ or Argon2; identical error for unknown user and wrong password.
  • Validate every input at the boundary; never trust a client-supplied id without an ownership check.
  • No secrets, stack traces or exception messages in responses.
  • Actuator internal-only.
  • Rate limit authentication endpoints.
  • Dependency scanning in CI — most breaches are an unpatched library, not your code.
  • Security tests for anonymous, wrong role and correct role on every protected route.

Configuration hygiene

  • @ConfigurationProperties with @Validated, so bad config fails at startup.
  • Profiles describe environments, not customers or features.
  • One artifact for every environment; only variables change.
  • spring.application.name always set.
  • No @Value scattered through business classes.

Code review checklist

  • ☐ Constructor injection; all dependency fields final.
  • ☐ No annotated method called via this.
  • ☐ Controller returns a DTO, never an entity.
  • ☐ @Transactional is on the service, and the method is public.
  • ☐ New queries have a fetch strategy and an index.
  • ☐ New endpoints have a security rule and a security test.
  • ☐ New outbound calls have timeouts and a failure path.
  • ☐ New config is validated and documented.
  • ☐ Migrations are backwards compatible with the running release.
  • ☐ No secrets, no personal data in logs.
  • ☐ Tests use the smallest context that proves the behaviour.
  • ☐ Page sizes bounded.

Keeping up with releases

PracticeWhy
Upgrade the patch version monthlyAlmost always zero-effort, and it is where security fixes land
Upgrade the minor version quarterlySmall deprecations are far cheaper than a two-year jump
Read the migration guide before a majorBoot 2 → 3 moved to jakarta.* and required Java 17
Use OpenRewrite for mechanical migrationsHandles most package renames automatically
Watch the support timelineOpen-source support windows are about a year per minor release

Which single change prevents the largest class of Spring Boot bugs?

Constructor injection makes dependencies explicit and final, turns circular dependencies into a startup failure instead of a runtime surprise, and lets you unit test with plain new. It costs nothing and eliminates several categories of problem at once.