Best practices · Stacks and tools
Spring Boot Best Practices
Opens with creditsA practical guide to Spring Boot best practices for Java developers building REST services. It covers versions and the new modular starters, dependency injection and structure, typed configuration, the web layer and error responses, JPA and transactions, virtual threads, securing Actuator, testing with slices and Testcontainers, and running cleanly in production.
What you will learn
9 chapters · about 21 min
1Versions, starters and dependenciesWhich Spring Boot and Java versions to run, how the modular starters in Spring Boot 4 work, and how to keep dependency versions consistent.4 practices · 3 min
2Structure and dependency injectionHow to organise packages and wire beans so the code stays testable and the application context stays easy to reason about.4 practices · 2 min
- Configuration and profilesHow to bind settings into typed, validated objects, keep secrets out of the repository and use profiles without creating a separate app per environment.4 practices · 2 minOpens with credits
- The web layer: DTOs, validation and errorsHow to shape requests and responses, validate input, return consistent error bodies and call other services without hanging.5 practices · 3 minOpens with credits
- Data access with JPA and transactionsThe JPA defaults and patterns that cause most production performance and correctness problems, and what to use instead.5 practices · 3 minOpens with credits
- Virtual threads and performanceWhen to switch on virtual threads, what changes when you do, and the settings that matter more than any code tweak.3 practices · 2 minOpens with credits
- Security and ActuatorHow to keep Spring Security on and Actuator endpoints from becoming the easiest way into your service.4 practices · 2 minOpens with credits
- TestingHow to test Spring Boot apps quickly: unit tests without Spring, slice tests for one layer, and full tests against real services in containers.4 practices · 2 minOpens with credits
- Running in productionShutdown, health probes, observability and container images: the settings that decide how a Spring Boot service behaves on deploy day.4 practices · 2 minOpens with credits
About this guide
Spring Boot best practices are mostly about knowing what the framework does for you, and where its defaults stop being the right answer. Boot makes a working REST service a few annotations away, and the same convenience hides a lot: an open session that lazy-loads data during JSON rendering, @Transactional that silently does nothing on an internal call, or an Actuator endpoint that hands out every environment variable once someone widens the exposure list.
This guide starts with the setup: a supported Spring Boot and Java version and the modular starters that arrived in Spring Boot 4. It then covers constructor injection and package structure, typed configuration with @ConfigurationProperties, the web layer and RFC 9457 error responses, data access with JPA and transactions, virtual threads and connection pools, securing Actuator, testing with slices and Testcontainers, and shutting down cleanly in production.
Everything here was checked against the Spring Boot 4.1 reference documentation (current release 4.1.1), which requires Java 17 and supports up to Java 26, and against the Spring Boot 4.0 migration guide. If you are still on 3.x, the version chapter explains the upgrade path.
Common questions
What is the latest version of Spring Boot?
As of October 2026 the current release is Spring Boot 4.1.1. It requires Java 17 or later, supports up to Java 26 and builds on Spring Framework 7. Check spring.io for the current version before starting a project.
Should I use field injection or constructor injection in Spring?
Use constructor injection. Dependencies are visible in the constructor, fields can be final and tests can create the class without Spring. A class with a single constructor does not need @Autowired.
What replaces @MockBean in Spring Boot 4?
Spring Boot 4 removed @MockBean and @SpyBean. Use @MockitoBean and @MockitoSpyBean from Spring Framework on test class fields. For plain unit tests, use Mockito @Mock with MockitoExtension.
Should I turn off spring.jpa.open-in-view?
Usually yes. It is on by default in web apps and lets lazy loading run during view rendering, which hides extra queries and holds a database connection for the whole request. Turn it off and load what each response needs inside the service.
Are virtual threads worth enabling in Spring Boot?
For services that mostly wait on databases and HTTP calls, often yes. Set spring.threads.virtual.enabled=true on Java 21 or later; the Boot docs strongly recommend Java 24 or later. Then size the connection pool and downstream limits carefully, since thread pools no longer cap concurrency.
Which Actuator endpoints are safe to expose?
By default only health is exposed over HTTP. Add only what you use, such as info and a metrics endpoint, preferably on a separate management port. Never expose env, heapdump or * on a public port.
Sources (8)
Checked against these, last on 13 October 2026.
- System Requirements, Spring Boot docsdocs.spring.io/spring-boot/system-requirements.html
- Spring Boot 4.0 Migration Guide, Spring Bootgithub.com/spring-projects/spring-boot/wiki/Spring-Boot-4.0-Migration-Guide
- SpringApplication, Spring Boot docsdocs.spring.io/spring-boot/reference/features/spring-application.html
- Servlet Web Applications, Spring Boot docsdocs.spring.io/spring-boot/reference/web/servlet.html
- SQL Databases, Spring Boot docsdocs.spring.io/spring-boot/reference/data/sql.html
- Endpoints, Spring Boot docsdocs.spring.io/spring-boot/reference/actuator/endpoints.html
- Testcontainers, Spring Boot docsdocs.spring.io/spring-boot/reference/testing/testcontainers.html
- Graceful Shutdown, Spring Boot docsdocs.spring.io/spring-boot/reference/web/graceful-shutdown.html
Related on Sefism
Picked from the other libraries by shared topics.
Roadmaps
See allCheat sheets
See allBest practices
See all- ASP.NET Core Best PracticesBuild fast, safe ASP.NET Core 10 APIs: DI lifetimes, validated options, minimal APIs, problem details, async rules, EF Core, rate limits, tests and health checks.
- TypeScript Best PracticesModern TypeScript best practices for 2026: strict settings, TypeScript 7, modeling data with unions, safe narrowing, runtime validation, generics and typed linting.
- Secure Coding Best PracticesWrite code that resists attack: untrusted input, validation, parameterized queries, output encoding, safe parsing, uploads, SSRF and errors that fail closed.
Checklists
See all- Production Readiness ChecklistCheck a service before it takes real traffic: ownership, SLOs, capacity, timeouts and retries, alerts, rollout and rollback, backups, security and on-call.
- API Security ChecklistCheck your REST or GraphQL API against the OWASP API Security Top 10: authentication, object authorization, rate limits, input validation, SSRF, CORS and logging.
- Database Migration ChecklistCheck a schema or data migration before it ships: expand and contract, lock behaviour, online indexes, batched backfills, rehearsal on real data, backups, rollback, deploy order and monitoring.
Project structures
See all- Express with TypeScript project structureFor students who know a bit of JavaScript and want a backend that looks like the ones teams actually run. Express gives you almost no structure, so this layout supplies it: one folder per feature under src/modules, each split into routes, controller, service and repository, with Zod at the edge and Vitest plus Supertest for tests.
- NestJS project structureFor people who want a structured TypeScript backend with clear rules about where code goes. Every feature is a Nest module that owns its controller, service, DTOs, entities and tests, so the app grows by adding folders, not by stretching old ones. The tree follows one orders API from nest new to a codebase a whole team can run for years.
- FastAPI project structureA typed Python API for an orders app, built the way the FastAPI docs and the official full stack template lay it out: one
apppackage, a router per feature, Pydantic schemas at the edges, services in the middle and SQLAlchemy models with Alembic migrations underneath. For students who have finished the FastAPI tutorial and want to know where the second, tenth and fiftieth file go.
Career questions
See all- Should I use PostgreSQL or MongoDB for my project?For most student and startup projects, PostgreSQL is the safer default: relational data, joins, constraints and transactions fit most apps, and it handles JSON and vector search too. MongoDB is a good fit when your data is naturally document-shaped and varies a lot, or your team already knows it well. Model your data first, then choose.
- Should I use Firebase or Supabase for my app?Both let you ship an app fast with auth, a database, storage and hosting-style services. Supabase is built on PostgreSQL, so it suits relational data and SQL skills you will reuse anywhere. Firebase is a mature Google platform with a document database and strong mobile tooling. Choose by your data shape, your platform, and how much you want to learn transferable database skills.
- How do I learn system design as a student or junior developer?Start with the building blocks you already touch: HTTP, databases, indexes, caching and queues. Then study how real systems are built through engineering blogs, and practise by redesigning your own projects for more users. Classic design problems come last, once the fundamentals make sense.
Stuck on something specific?
Writing only gets you so far. If you want an answer to your situation rather than the general case, book a session and we will work through it together. Sessions are free for approved Sefism members, and a few slots open each week.
- 1:1 Mentorship
- Fresh Graduate Mentorship
- Career Guidance
Brand deals, promos and partnerships: tauseeffayyaz@gmail.com