Contrasting Spring Framework and Spring Boot
Medium · Coding & Algorithms · Software Engineer · Online Assessment
Prompt
Explain how the core Spring Framework and Spring Boot relate to each other and where they diverge in day-to-day backend engineering. Walk through how each approach handles application wiring, conditional bean setup, library version curation, sensible out-of-the-box conventions, HTTP server hosting, process bootstrap order, and real-world project fit.
Scope & Expectations
- Architecture & wiring: Clarify how Spring Boot layers onto Spring's core container and contrast explicit bean registration against externalized property binding and condition-driven auto-configuration.
- Dependencies, defaults & packaging: Compare manual library alignment and external servlet-container deployments against starter modules, managed Bills of Materials (BOMs), convention-over-configuration defaults, and self-contained executable archives with embedded servers.
- Bootstrap sequence & trade-offs: Trace the startup lifecycle side by side from JVM entry to serving traffic, and outline concrete scenarios where teams should pick Spring Boot versus plain Spring Framework.
Step-by-step walkthrough
How Spring Framework and Spring Boot fit together
Spring Boot is neither a competing framework nor a rewrite of Spring — it is an opinionated assembly and runtime layer built directly on top of the Spring Framework.
- Spring Framework provides the core programming model: the IoC (Inversion of Control) container (
ApplicationContext, a central registry that creates and manages application objects called beans), Dependency Injection (DI) (passing collaborators into a class's constructor instead of hardcodingnew), AOP (Aspect-Oriented Programming) (wrapping cross-cutting logic like@Transactionaldatabase commits around methods via runtime proxies), Spring MVC / WebFlux web routing, and data-access abstractions. - Spring Boot automates the tedious plumbing around that core: choosing compatible library versions, auto-creating infrastructure beans from what is on the classpath, embedding the HTTP server inside your JAR, binding external environment settings, and exposing production health endpoints.
+-----------------------------------------------------------------------+ | Your Business Code (@RestController, @Service) | +-----------------------------------------------------------------------+ | Spring Boot Layer: Starters + Auto-Config + Embedded Server + Ops | +-----------------------------------------------------------------------+ | Spring Framework Core: IoC Container (DI) + AOP + MVC + Transactions | +-----------------------------------------------------------------------+ | Java Virtual Machine | +-----------------------------------------------------------------------+Every Spring Boot app is a Spring app (
@Component,@Autowired,@RestController, and@Transactionalbehave identically). What changes is who writes the wiring code and how the process boots:Dimension Plain Spring Framework Spring Boot (3.x) Infrastructure beans Hand-declared in @Configurationclasses or XMLAuto-configured conditionally; override only what differs Web server & artifact Package a .wardeployed into an external serverEmbedded Tomcat inside a standalone executable .jarDependency versions Align third-party library versions manually Starter bundles + managed BOM version table Process entry point External servlet container loads your app Your own main()callsSpringApplication.run(...)Production monitoring Assemble health/metrics libraries manually Built-in Actuator health probes and Micrometer metrics - Spring Framework provides the core programming model: the IoC (Inversion of Control) container (
Manual bean configuration vs externalized properties
In plain Spring, even a tiny web service with a SQL database requires you to explicitly enable Spring MVC, enable transaction management, configure a connection pool, wire
JdbcTemplate, wire a transaction manager, and register theDispatcherServlet:@Configuration @EnableWebMvc @EnableTransactionManagement @ComponentScan("com.example.shop") @PropertySource("classpath:db.properties") public class AppConfig { @Bean public DataSource dataSource(Environment env) { HikariConfig config = new HikariConfig(); config.setJdbcUrl(env.getRequiredProperty("db.url")); config.setUsername(env.getRequiredProperty("db.user")); config.setPassword(env.getRequiredProperty("db.password")); return new HikariDataSource(config); } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } @Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] { AppConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }In Spring Boot, that entire infrastructure block disappears behind
@SpringBootApplicationplus three lines of externalized configuration:@SpringBootApplication public class ShopApplication { public static void main(String[] args) { SpringApplication.run(ShopApplication.class, args); } }# src/main/resources/application.properties spring.datasource.url=jdbc:postgresql://localhost:5432/shop spring.datasource.username=shop spring.datasource.password=${DB_PASSWORD}Boot's externalized configuration lets the exact same compiled JAR run in local dev, staging, and Kubernetes by layering property sources in a strict precedence order. Trace
server.portacross five common sources from lowest to highest priority:Priority Source Value Winner? -------- ------------------------------------------------- ----- ------- 1 (low) Spring Boot built-in default 8080 2 application.properties (packaged in JAR) 8081 3 application-prod.properties (when profile=prod) 8443 4 OS environment variable SERVER_PORT 9090 5 (high) CLI argument --server.port=7070 7070 <-- Active port is 7070 Drop the CLI flag -> falls back to 9090 (SERVER_PORT maps to server.port via relaxed binding) Also unset SERVER_PORT -> falls back to 8443 (active profile file beats base application.properties) Deactivate prod profile -> falls back to 8081For structured groups of settings, bind them onto a validated Java class or record with
@ConfigurationProperties(prefix = "shop.payment")rather than scattering@Valuestrings across services.Auto-configuration: condition checks, not magic
Beginners sometimes treat auto-configuration as mysterious black-box magic, but it is just ordinary Spring
@Configurationclasses guarded by@Conditional...annotations.@SpringBootApplicationincludes@EnableAutoConfiguration, which reads candidate classes listed inMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports(introduced in Boot 2.7 and required in Boot 3.x, replacing the olderMETA-INF/spring.factoriesentry). Crucially, Boot evaluates auto-configurations after registering your own@Configurationand@Componentclasses:Candidate @AutoConfiguration class | +--> @ConditionalOnClass(HikariDataSource.class) Is the library JAR on the classpath? --No--> Skip | Yes +--> @ConditionalOnProperty("audit.enabled=true") Is the feature toggle enabled? --No--> Skip | Yes +--> @ConditionalOnMissingBean(AuditLogger.class) Did the developer define their own? --Yes-> Back off! No v Register default bean in ApplicationContextAny internal platform team can publish a custom auto-configuration using the exact same rules:
@AutoConfiguration @ConditionalOnProperty(prefix = "audit", name = "enabled", havingValue = "true", matchIfMissing = true) public class AuditAutoConfiguration { @Bean @ConditionalOnMissingBean public AuditLogger auditLogger() { return new Slf4jAuditLogger(); } }Trace what Boot's
DataSourceAutoConfigurationdoes whenspring-boot-starter-jdbcis present:What is on classpath / in properties Resulting behavior ------------------------------------------------------------ ------------------------------------------------------- H2 driver on classpath, no spring.datasource.url set Creates HikariCP pool pointing at in-memory H2 database PostgreSQL driver on classpath + spring.datasource.url set Creates pooled HikariCP DataSource to PostgreSQL You declare your own @Bean DataSource Boot's DataSource auto-config backs off completely No embedded DB driver on classpath and no URL configured Fails fast on startup explaining why DataSource failedTo inspect or override decisions without guessing, run with
--debug(or expose Actuator'sconditionsendpoint) to print the exact Condition Evaluation Report showing every matched and skipped class, or disable unwanted classes via@SpringBootApplication(exclude = DataSourceAutoConfiguration.class).Embedded servers and executable JARs vs external WARs
A servlet container (such as Apache Tomcat or Eclipse Jetty) is the HTTP server engine that opens network sockets, manages worker threads, and translates raw HTTP bytes into Java
HttpServletRequestcalls. Classic Spring and Spring Boot invert where that server lives:Classic Spring (External WAR) Spring Boot (Executable "Fat" JAR) +-----------------------------------------+ +-----------------------------------------+ | Pre-installed Shared Tomcat JVM | | Container / Host Process (java -jar) | | configured via Tomcat's server.xml | | +-----------------------------------+ | | +---------------+ +---------------+ | | | shop.jar | | | | shop.war | | billing.war | | | | - Your classes + dependencies | | | +---------------+ +---------------+ | | | - Embedded Tomcat library | | +-----------------------------------------+ | +-----------------------------------+ | +-----------------------------------------+- Plain Spring: Ops installs and tunes an external Tomcat server, and your build produces a WAR (Web Application Archive) deployed into it.
- Spring Boot: Tomcat is just another library pulled in by
spring-boot-starter-web. Your build packages an executable ("fat") JAR containing your compiled code, all dependency JARs, and Boot'sJarLauncher. You launchjava -jar shop.jarand tune server settings (server.port,server.tomcat.threads.max,server.ssl.*) inapplication.propertiesor environment variables — matching the one-process-per-container model of Docker and Kubernetes.
Swapping Tomcat for Jetty is purely a build-file change (and reactive
spring-boot-starter-webfluxapps default to non-blocking Reactor Netty instead):<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency>Starter bundles, BOM dependency management, and opinionated defaults
In plain Spring, adding web + JSON + database support means hunting down compatible versions of Spring MVC, Jackson, Hibernate, HikariCP, SLF4J, Logback, and JUnit by hand — where one mismatched minor version triggers
NoSuchMethodErrorat runtime. Spring Boot eliminates "dependency hell" with two tools:- Starters — one-line capability bundles:
spring-boot-starter-web: Spring MVC + Jackson JSON + embedded Tomcat + logging.spring-boot-starter-data-jpa: Spring Data JPA + Hibernate + HikariCP + JDBC.spring-boot-starter-test: JUnit Jupiter + Mockito + AssertJ + Spring Test.
- A curated BOM (Bill of Materials) —
spring-boot-dependenciespins a pre-tested matrix of versions across Spring and hundreds of third-party libraries. Inheritingspring-boot-starter-parent(or importing the BOM in Maven/Gradle) lets you omit<version>tags on managed libraries:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.3.5</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.postgresql</groupId> <artifactId>postgresql</artifactId> <scope>runtime</scope> </dependency> </dependencies>Alongside managed versions, Boot applies opinionated defaults ("convention over configuration"): port
8080, Jackson for JSON (ISO-8601dates configurable via properties), Logback for console logging, HikariCP for fast connection pooling, static file serving fromclasspath:/static/, structured/errorresponses, and secure-by-default authentication wheneverspring-boot-starter-securityis on the classpath. Every single choice can be overridden via properties or a custom@Bean.- Starters — one-line capability bundles:
Startup flow side by side
Comparing what happens from process launch to the first HTTP request highlights how Boot wraps — rather than replaces — Spring's core container refresh:
Plain Spring MVC (External Tomcat + WAR) 1. External Tomcat process starts and unpacks shop.war. 2. Servlet 3.0+ container discovers SpringServletContainerInitializer on the classpath. 3. Initializer invokes your WebAppInitializer, registering DispatcherServlet. 4. ApplicationContext.refresh() runs: load @Configuration / XML -> run BeanFactoryPostProcessors (@ComponentScan, @Bean) -> register BeanPostProcessors (@Transactional proxies) -> instantiate singleton beans. 5. Tomcat routes traffic according to its external server.xml port. Spring Boot (Executable JAR) 1. java -jar shop.jar starts Boot's JarLauncher, which invokes your main() method. 2. SpringApplication.run() inspects the classpath to pick web type (SERVLET, REACTIVE, or NONE). 3. Builds the layered Environment (CLI flags > OS env vars > profile files > application.properties). 4. Creates AnnotationConfigServletWebServerApplicationContext and calls refresh(): - Registers your @Configuration and @ComponentScan beans FIRST; - Evaluates @AutoConfiguration candidates whose @Conditional checks pass; - Instantiates embedded Tomcat during refresh and binds port 8080 once singletons are ready. 5. Executes CommandLineRunner / ApplicationRunner beans and publishes ApplicationReadyEvent.Production observability and testing slices
Plain Spring leaves operational endpoints and sliced test harnesses for your team to assemble manually; Spring Boot ships them out of the box:
- Spring Boot Actuator: Adds
/actuator/health(including separate Kuberneteslivenessandreadinessprobes), Micrometer metrics export (to Prometheus, Datadog, OpenTelemetry), runtime log-level toggling (/actuator/loggers), andconditions. For safety, Boot 3.x exposes onlyhealthover HTTP by default; sensitive endpoints likeenvorheapdumpmust be explicitly enabled and locked behind authentication. - Fast test slices:
@SpringBootTestboots the entire application context for integration tests, while focused slices like@WebMvcTest(controllers + MockMvc only) and@DataJpaTest(repositories + test database only) start in a fraction of the time. - Spring Boot 3.x platform features: Requires Java 17+, uses Jakarta EE (
jakarta.*instead ofjavax.*), supports Java 21 virtual threads (spring.threads.virtual.enabled=truein Boot 3.2+), and supports GraalVM native-image compilation via ahead-of-time (AOT) bean processing.
- Spring Boot Actuator: Adds
Choosing between Spring Boot and standalone Spring
Choose Spring Boot as the default for almost every standalone service: - Microservices and REST / GraphQL / gRPC APIs deployed in Docker or Kubernetes; - Scheduled batch jobs, Kafka consumers, and CLI tools (
spring.main.web-application-type=none); - Internal enterprise services (such as trading, ledger, or reporting backends at regulated financial institutions) where standardized health probes, logging, and dependency governance across hundreds of repos save enormous maintenance effort.Choose plain Spring Framework (without Boot) in three specific situations: - Legacy shared-server WAR estates running on centrally operated WebLogic, WebSphere, or shared Tomcat clusters where migrating deployment pipelines is not justified. - Reusable shared libraries or SDKs that should work in any Spring app without forcing a specific Spring Boot version onto consumers (best practice: publish a lightweight
my-lib-coreusing plain Spring, plus an optionalmy-lib-spring-boot-startermodule containing@AutoConfiguration). - Strictly explicit architectures where platform policy forbids classpath-triggered auto-configuration and mandates hand-written wiring for every bean.
Intuition & how it works
Think of the Spring Framework as buying lumber, copper pipes, and electrical wire from separate aisles of a hardware store, and Spring Boot as ordering a pre-engineered modular house kit built from those exact same materials. Under the hood, both houses run on the same foundation — Spring's IoC (Inversion of Control) container (the central registry that creates Java objects called beans and injects their dependencies), AOP (runtime proxies for @Transactional and security), and Spring MVC. Spring Boot simply pre-wires the standard plumbing with sensible defaults that step aside the moment you supply your own custom fixture.
Assembling plain Spring services from scratch scales poorly once an engineering org grows past one monolith. Every new service requires dozens of lines of boilerplate Java/XML config (DataSource, JdbcTemplate, TransactionManager, DispatcherServlet), manual version-matching across Jackson, Hibernate, HikariCP, and Tomcat, and an externally installed servlet server before a single "Hello" route can run. One mismatched transitive JAR version surfaces as a cryptic runtime crash.
Walk through how Spring Boot turns that setup into a deterministic three-step startup for a PostgreSQL web service:
1. Dependencies & server: Adding spring-boot-starter-web, spring-boot-starter-jdbc, and postgresql pulls in compatible library versions from Boot's BOM (Bill of Materials) plus an embedded Tomcat server inside one executable JAR.
2. Conditional auto-wiring: On SpringApplication.run(...), Boot registers your @RestController and @Service beans first, then evaluates auto-configurations — seeing HikariDataSource on the classpath and no custom DataSource bean, it creates a pooled PostgreSQL DataSource automatically.
3. Layered config override: If application.properties sets server.port=8081, application-prod.properties sets 8443, SERVER_PORT=9090 is in the OS environment, and --server.port=7070 is passed on the command line, Boot's precedence rules deterministically bind port 7070.
Key points
- Layer, not replacement: Every Spring Boot app is a Spring Framework app;
@Component,@Autowired,@Transactional, and@RestControllercome straight from Spring Framework, while Boot handles assembly, configuration, packaging, and operations. - Manual wiring vs externalized config: Plain Spring declares infrastructure beans in
@Configurationclasses or XML; Boot auto-creates them and tunes behavior through layered external properties (CLI args > OS env vars > active-profile files > application.properties > built-in defaults). - Condition-guarded auto-configuration: Candidate
@AutoConfigurationclasses (listed inAutoConfiguration.importsin Boot 2.7+ / 3.x) use@ConditionalOnClass,@ConditionalOnProperty, and@ConditionalOnMissingBean— running after user config so any@Beanyou define automatically wins. - Embedded server vs external WAR: Boot embeds Tomcat (or Jetty / Reactor Netty) inside a standalone executable "fat" JAR launched via
java -jar, whereas classic Spring packages a WAR (Web Application Archive) deployed into a pre-installed external servlet container. - Starters, BOM, and opinionated defaults:
spring-boot-starter-*modules bundle capabilities,spring-boot-dependenciespins tested library versions, and sensible defaults (port8080, HikariCP, Jackson, Logback, Actuator/actuator/health) work out of the box while remaining 100% overridable. - Inverted startup flow: In plain Spring MVC, the external servlet container starts first and bootstraps Spring's context; in Spring Boot, your
main()method boots Spring's context first, which creates and starts the embedded server near the end of container refresh. - When to choose which: Default to Spring Boot for new microservices, APIs, containers, and batch jobs; use plain Spring for legacy shared-WAR servers or reusable core libraries that should not force Boot onto callers.
Common mistakes
- Calling Spring Boot a separate replacement for Spring: Boot cannot exist without Spring Framework's
ApplicationContext, dependency injection, and MVC/WebFlux engines underneath it. - Dismissing auto-configuration as unexplainable "magic": Interviewers expect you to name
@ConditionalOnClassand@ConditionalOnMissingBean, explain why user beans take priority, and mention--debug(the Condition Evaluation Report). - Adding
@EnableWebMvcto a Spring Boot app by habit:@EnableWebMvcregistersWebMvcConfigurationSupport, which causes Boot'sWebMvcAutoConfiguration(@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)) to back off completely — silently breaking default Jackson customizations and static resource serving. - Placing
@SpringBootApplicationinside a narrow sub-package:@ComponentScandefaults to scanning the main class's package and below, so puttingShopApplicationincom.example.shop.websilently ignores@Serviceclasses incom.example.shop.orders. - Adding starters "just in case": Classpath presence triggers behavior — adding
spring-boot-starter-securityimmediately locks every HTTP route behind authentication, and addingspring-boot-starter-data-jpawithout database settings fails startup. - Hand-overriding dozens of dependency versions: Defeats Boot's tested BOM compatibility matrix and reintroduces
NoSuchMethodErrormismatches. - Exposing all Actuator endpoints publicly without auth: Boot 3 exposes only
healthby default for good reason — openingheapdumpleaks live JVM memory (including tokens and passwords), and enabling unmaskedenvexposes configuration secrets.
Follow-up questions
- What annotations are combined inside
@SpringBootApplication, and why does its package placement matter?@SpringBootApplicationis a meta-annotation combining three annotations:@SpringBootConfiguration(a specialized@Configurationmarking the primary config class),@EnableAutoConfiguration(importing conditional auto-configurations fromAutoConfiguration.imports), and@ComponentScan(scanning the main class's package and all sub-packages for@Component,@Service,@Repository, and@Controllerbeans). Keeping the main class in your root package (com.example.shop) ensures component scanning discovers every module cleanly instead of silently skipping sibling packages. - How should you customize or turn off an auto-configured bean in Spring Boot without breaking unrelated defaults? Start with the lightest touch: set an
application.propertieskey (such asspring.datasource.hikari.maximum-pool-size=20) or register a*Customizerbean (likeJackson2ObjectMapperBuilderCustomizer) so you keep Boot's defaults while tweaking one detail. If you need full control of a single bean, declare your own@Beanof that interface/type so Boot's default backs off via@ConditionalOnMissingBean; to disable an entire auto-configuration class, use@SpringBootApplication(exclude = ...)orspring.autoconfigure.excludeand verify in the--debugreport. - How do you package and deploy a Spring Boot service as a traditional WAR inside an external servlet container? Change build packaging from
jartowar, markspring-boot-starter-tomcatasprovidedscope so the embedded server does not conflict with the external container's classes, and make your main class extendSpringBootServletInitializeroverridingconfigure(SpringApplicationBuilder)to registerShopApplication.class. Note that Spring Boot 3.x migrated fromjavax.servlettojakarta.servlet, so the external server must be Jakarta EE 9/10 compatible (such as Apache Tomcat 10.1+).
Follow-up questions
- What annotations are combined inside @SpringBootApplication, and why does its package placement matter?
- How should you customize or turn off an auto-configured bean in Spring Boot without breaking unrelated defaults?
- How do you package and deploy a Spring Boot service as a traditional WAR inside an external servlet container?
Similar questions
- Core Language and Library Upgrades in Java 8
- Multithreading Primitives and Concurrency Control in Java
- Role Fit, Engineering Differentiators, Pain Points, and Stack Versions
- Designing Effective Tests and Scoped Integration Suites
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger