ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 4 · Spring & Spring Boot
  4. Volume I
  5. Spring Framework Architecture
Book 4 · Volume I — Spring Core, IoC & Dependency Injection · Topic 1.2

Spring Framework Architecture

The functional building blocks of Spring — from the core container up to web, data, security and integration

12 min readStage 2 · Frameworks & design8 interview questions
Chapter
Chapter 1 — Spring Framework Fundamentals
Prerequisites
Topic 1.1 (why Spring exists)
You will be able to
Draw Spring's architecture from memory, name the responsibility of each building block, and explain how they cooperate in a single request
Covers
Spring Core · Spring Context · Spring Beans · Spring Expression Language · Spring AOP · Spring Web · Spring Data · Spring Security · Spring Integration
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 4A. Deep Dive — The Container Is the Architecture
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 10. Interview Questions & Answers

1Concept / Definition

Spring Framework architecture is the arrangement of Spring's functional building blocks and the dependency rules between them. At its heart sits the Core Container (Core, Beans, Context, Expression Language). Every other capability — AOP, web, data access, messaging, testing — is implemented as a set of beans and extension points plugged into that container.

The TOC for this topic lists nine building blocks. Six of them (Core, Context, Beans, SpEL, AOP, Web) are parts of the Spring Framework itself. Three (Spring Data, Spring Security, Spring Integration) are separate Spring projects that build on the Framework. Knowing this boundary is important: the Framework has its own release train (7.0.x), while each project has its own versions, aligned through Spring Boot.

Layered view of Spring's architecture
Figure 1 — Layered view of Spring's architecture

2Why It Exists

A layered, container-centric architecture answers three design goals that were explicit from Spring's first release:

  • Selective adoption. Teams can use the container alone, or add only JDBC support, or only MVC — without dragging in unrelated infrastructure.
  • Uniform extension. Web, data and security features are delivered as beans plus post-processors, so they are configured, overridden and tested in exactly the same way as application code.
  • Replaceability. Because higher layers depend on abstractions in lower layers (for example, PlatformTransactionManager), implementations can change without affecting callers.

3Core Concepts

3.1 Spring Core (`spring-core`)

The lowest layer, containing the utilities every other module uses. It has no concept of beans.

  • Resource abstraction — Resource, ResourceLoader, classpath:/file:/https: handling (Topic 8.4).
  • Type conversion — ConversionService, Converter<S,T>, TypeDescriptor.
  • Environment basics — PropertyResolver interfaces used by Environment.
  • Annotation utilities — MergedAnnotations, meta-annotation and attribute-alias support that make composed annotations like @RestController possible.
  • Repackaged libraries — ASM (bytecode reading) and Objenesis (instantiation without constructors) used for scanning and CGLIB proxies.
  • Null-safety — in Spring Framework 7, APIs are annotated with JSpecify @Nullable/@NullMarked; Spring's own org.springframework.lang.Nullable is deprecated.

3.2 Spring Beans (`spring-beans`)

The module that knows how to create and wire objects.

  • BeanFactory — the root container interface: getBean, containsBean, isSingleton, getType (Topic 3.1).
  • BeanDefinition — the recipe: class, scope, constructor arguments, property values, init/destroy methods, lazy flag, primary flag (Topic 4.1).
  • DefaultListableBeanFactory — the workhorse implementation used by every ApplicationContext.
  • BeanWrapper and property binding — set properties by name, with type conversion.
  • BeanPostProcessor, BeanFactoryPostProcessor contracts — the extension hooks (Chapter 5).

3.3 Spring Context (`spring-context`)

Builds an application-level container on top of beans.

  • ApplicationContext — adds events, MessageSource (i18n), resource loading, Environment and profiles, and automatic registration of post-processors (Topic 3.2).
  • Annotation configuration — @Configuration, @Bean, @ComponentScan, @Import, @Profile, @Conditional.
  • Enterprise services built on the container: scheduling (@Scheduled, TaskExecutor), @Async, the caching abstraction (@Cacheable), JMX export, validation integration.
  • In Framework 7: the resilience features @Retryable and @ConcurrencyLimit (enabled with @EnableResilientMethods), and BeanRegistrar for programmatic bean registration.

3.4 Spring Expression Language (`spring-expression`)

A runtime expression language for querying and manipulating object graphs (Topic 8.5).

  • Used in @Value("#{...}"), Spring Security (@PreAuthorize("hasRole('ADMIN')")), caching keys (@Cacheable(key = "#id")) and conditional listeners.
  • Supports property access, method calls, operators, collection selection/projection, bean references (@beanName) and ternary/Elvis operators.

3.5 Spring AOP (`spring-aop`)

Proxy-based aspect-oriented programming.

  • Creates JDK dynamic proxies (for interfaces) or CGLIB subclasses (for classes) around beans.
  • Uses AspectJ's pointcut syntax (execution(* com.acme..*Service.*(..))) but not AspectJ weaving unless you opt in.
  • Is the mechanism behind @Transactional, @Cacheable, @Async, @Validated, method security and the resilience annotations.

3.6 Spring Web (`spring-web`, `spring-webmvc`, `spring-webflux`)

  • spring-web — shared HTTP infrastructure: HttpMessageConverter, RestClient, WebClient contracts, HTTP interface clients (@HttpExchange), multipart, CORS.
  • spring-webmvc — the Servlet stack: DispatcherServlet, @Controller/@RestController, handler mappings, view resolution. In Framework 7, requires Servlet 6.1 (Jakarta EE 11).
  • spring-webflux — the reactive, non-blocking stack on Reactor (Netty or Servlet containers).
  • Framework 7 adds first-class API versioning (@GetMapping(version = "1.2")) for both stacks.

3.7 Spring Data (separate project)

A family of projects (Spring Data JPA, JDBC, MongoDB, Redis, Cassandra, Elasticsearch, R2DBC…) that provides a repository abstraction: you declare an interface, and Spring Data generates the implementation at runtime from method names, @Query annotations or query-by-example. It builds on the Framework's spring-tx, spring-orm and spring-jdbc.

3.8 Spring Security (separate project)

Authentication and authorization for Servlet and reactive applications. At its core is a SecurityFilterChain of Servlet filters (registered via DelegatingFilterProxy), plus method security implemented with Spring AOP. It supports form login, HTTP Basic, OAuth2/OIDC login, resource servers with JWT, SAML 2.0, and passkeys (WebAuthn).

3.9 Spring Integration (separate project)

An implementation of the Enterprise Integration Patterns (Hohpe & Woolf) on top of the container: message channels, endpoints, routers, splitters, aggregators, transformers and adapters for files, FTP, JMS, AMQP, Kafka, HTTP, JDBC and more. It builds on the Framework's spring-messaging abstractions (Message<T>, MessageChannel).

Building blockKindKey typesDepends on
Spring CoreFramework moduleResource, ConversionService, MergedAnnotationsJDK only
Spring BeansFramework moduleBeanFactory, BeanDefinitionCore
Spring ContextFramework moduleApplicationContext, @ConfigurationBeans, Core, AOP, SpEL
SpELFramework moduleExpressionParser, EvaluationContextCore
Spring AOPFramework moduleProxyFactory, Advisor, @Aspect supportBeans, Core
Spring WebFramework modulesDispatcherServlet, RestClientContext, Beans
Spring DataSeparate projectRepository, CrudRepository, @QueryFramework tx/orm/jdbc
Spring SecuritySeparate projectSecurityFilterChain, AuthenticationManagerFramework web, AOP
Spring IntegrationSeparate projectMessageChannel, IntegrationFlowFramework messaging
Table 1 — The nine building blocks at a glance

4How It Works Internally

4.1 The Core Container stack

The four modules of the Core Container and how they layer
Figure 2 — The four modules of the Core Container and how they layer

The Core Container is strictly layered. spring-core provides utilities; spring-beans uses them to implement the bean factory; spring-context wraps a bean factory with application-level services; spring-expression is used by context for #{...} evaluation. Crucially, every ApplicationContext delegates bean creation to an internal DefaultListableBeanFactory — the context adds services around it but does not reimplement it.

4.2 How higher layers plug in

Higher-level features follow one recurring recipe:

1. An enabling annotation or auto-configuration registers infrastructure bean definitions (for example, @EnableTransactionManagement registers a transaction advisor and an auto-proxy creator).

2. A post-processor inspects each bean as it is created and decides whether it needs special treatment (for example, "does this class have @Transactional methods?").

3. If so, the bean is wrapped in a proxy or registered with some infrastructure (a handler mapping, a listener container, a scheduler).

This is why Spring Web, Spring Security's method security, Spring Data repositories and Spring Integration flows all "feel" the same: they are all beans created and decorated by the same container machinery.

4.3 Cooperation in a single request

One HTTP request crossing several architectural building blocks
Figure 3 — One HTTP request crossing several architectural building blocks
JAVA
@RestController                                   // Spring Web: discovered as a handler
@RequestMapping("/orders")
class OrderController {
    private final OrderService service;            // Spring Context: injected bean
    OrderController(OrderService service) { this.service = service; }
 
    @PostMapping
    @PreAuthorize("hasAuthority('SCOPE_orders:write')")   // Security + SpEL + AOP
    ResponseEntity<OrderDto> create(@RequestBody @Valid OrderDto dto) {
        return ResponseEntity.status(201).body(service.place(dto));
    }
}
 
@Service
class OrderService {
    private final OrderRepository repo;             // Spring Data: generated implementation
    OrderService(OrderRepository repo) { this.repo = repo; }
 
    @Transactional                                  // AOP proxy + spring-tx
    OrderDto place(OrderDto dto) { return OrderDto.from(repo.save(dto.toEntity())); }
}
 
interface OrderRepository extends JpaRepository<Order, Long> {}   // no implementation written

4ADeep Dive — The Container Is the Architecture

A useful way to reason about Spring is that there are only three kinds of objects in a running application:

KindExamplesWho writes them
Application beansOrderService, OrderController, repositoriesYou (or Spring Data generates them)
Infrastructure beansDispatcherServlet, DataSourceTransactionManager, SecurityFilterChain, ObjectMapperFramework, usually registered by configuration or Boot auto-configuration
Container extension beansBeanPostProcessors (auto-proxy creator, @Autowired processor), BeanFactoryPostProcessors (ConfigurationClassPostProcessor, placeholder configurer)Framework; you rarely write them
Table 2 — The three kinds of objects in a Spring application

The third category is what makes the architecture work. For example, the AutowiredAnnotationBeanPostProcessor is what processes @Autowired and @Value; CommonAnnotationBeanPostProcessor handles @PostConstruct, @PreDestroy and @Resource; ConfigurationClassPostProcessor parses @Configuration, @ComponentScan and @Import. An annotation is inert until one of these processors is registered — which is why a plain DefaultListableBeanFactory (without a context) ignores @Autowired.

JAVA
// Diagnostic: list the infrastructure the container registered for you
try (var ctx = new AnnotationConfigApplicationContext(AppConfig.class)) {
    for (String name : ctx.getBeanDefinitionNames()) {
        var def = ctx.getBeanFactory().getBeanDefinition(name);
        if (def.getRole() == BeanDefinition.ROLE_INFRASTRUCTURE) {
            System.out.println("infra: " + name);
        }
    }
}
// Typical output:
// infra: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
// infra: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
// infra: org.springframework.context.annotation.internalCommonAnnotationProcessor
// infra: org.springframework.context.event.internalEventListenerProcessor
// infra: org.springframework.context.event.internalEventListenerFactory

5APIs / Features / Syntax

AreaEntry-point APIEnabling mechanism
ContainerAnnotationConfigApplicationContext, SpringApplication (Boot)@Configuration, @ComponentScan
Beans@Component, @Bean, BeanRegistrar (7.0)Component scanning, configuration classes
SpELSpelExpressionParser, #{...} in @ValueContext's StandardBeanExpressionResolver
AOP@Aspect, ProxyFactory@EnableAspectJAutoProxy (auto in Boot)
Transactions@Transactional, TransactionTemplate@EnableTransactionManagement
Web@RestController, RestClient, @HttpExchange@EnableWebMvc or Boot auto-config
DataJpaRepository, @Query@EnableJpaRepositories or Boot
SecuritySecurityFilterChain bean, @PreAuthorize@EnableWebSecurity, @EnableMethodSecurity
IntegrationIntegrationFlow DSL, @ServiceActivator@EnableIntegration
Table 3 — Entry points and enabling mechanisms per building block

The pattern @EnableXxx is itself architectural: each one is an @Import of a configuration class or an ImportSelector/ImportBeanDefinitionRegistrar that registers the infrastructure beans for that feature (Chapter 6.3).

6Practical Examples

6.1 A container-only application (no web, no Boot)

JAVA
@Configuration
@ComponentScan("com.acme.billing")
@EnableScheduling
class BillingConfig {
    @Bean
    Clock clock() { return Clock.systemUTC(); }
}
 
public class BillingApp {
    public static void main(String[] args) {
        var ctx = new AnnotationConfigApplicationContext(BillingConfig.class);
        ctx.registerShutdownHook();      // graceful destroy callbacks on JVM exit
        // @Scheduled beans now run; nothing else is required
    }
}

Only spring-context is needed on the classpath. This shows the architecture's selective-adoption goal: the container and scheduling work without any web or data layer.

6.2 Seeing SpEL, AOP and Context together

JAVA
@Service
class PriceService {
    @Value("#{systemProperties['region'] ?: 'EU'}")      // SpEL with Elvis operator
    private String region;
 
    @Cacheable(cacheNames = "prices", key = "#sku + ':' + #root.target.region")
    public BigDecimal priceFor(String sku) { /* expensive lookup */ return lookup(sku); }
 
    @Retryable(maxAttempts = 3)                           // Framework 7 core resilience (AOP)
    BigDecimal lookup(String sku) { /* remote call */ return BigDecimal.TEN; }
}

Note that lookup is called on this from priceFor, so the retry advice would not apply — a direct consequence of the proxy-based AOP architecture (Topic 1.1, Section 7).

7Common Problems & Mistakes

  • Confusing projects with modules. Stating that "Spring Security is a module of the Spring Framework" is inaccurate; it is a separate project with its own version (for example, Spring Security 7.x alongside Framework 7.x).
  • Annotations without their processor. Using @Autowired or @PostConstruct with a bare DefaultListableBeanFactory, or @Transactional without @EnableTransactionManagement (outside Boot), silently does nothing.
  • Mixing MVC and WebFlux accidentally. Having both spring-webmvc and spring-webflux on the classpath makes Spring Boot choose MVC; developers expecting a reactive server are surprised.
  • Assuming AOP intercepts everything. Proxy-based AOP only intercepts public (and, for CGLIB, non-private) method calls that arrive through the proxy — not constructors, not self-calls, not final methods on CGLIB proxies.
  • Leaking framework types into the domain. Placing ResponseEntity or Pageable deep in the domain layer couples business logic to the web or data building block.

8Performance & Production Considerations

Building blockTypical production concernMitigation
ContextStartup time from scanning and configuration parsingNarrow scan packages; AOT processing; avoid expensive @PostConstruct work
AOPProxy creation cost at startup; stack depth in tracesApply advice precisely; understand proxy chains when reading stack traces
SpELExpression parsing per call if misusedFramework caches parsed expressions; don't build expressions dynamically in hot paths
WebThread-per-request blockingEnable virtual threads (Boot: spring.threads.virtual.enabled=true) on Java 21+
DataN+1 queries hidden behind repositoriesFetch plans, projections, query logging
SecurityFilter-chain misordering, over-broad matchersExplicit SecurityFilterChain per path; test with MockMvc
Table 4 — Production concerns by architectural building block

9Architecture & Design Considerations

  • Mirror Spring's layering in your own code. Controllers (web) depend on services (context beans) which depend on repositories (data). Enforce this with ArchUnit or Spring Modulith rather than relying on discipline.
  • Keep the domain Spring-free where practical. Entities and domain services can be plain Java; Spring annotations belong at the edges (adapters, configuration). This is the hexagonal-architecture reading of Spring's POJO philosophy.
  • Use the container as the composition root. All wiring decisions belong in configuration classes, not scattered new calls.
  • Choose the web stack deliberately. MVC plus virtual threads now covers most I/O-bound workloads with a simpler programming model; WebFlux remains the choice for streaming and backpressure-heavy systems.

10Interview Questions & Answers

Q1L1 · BasicConcept

What are the modules of the Spring Core Container?

The Core Container consists of four modules: spring-core, spring-beans, spring-context and spring-expression. spring-core holds the low-level utilities, such as the resource abstraction, type conversion and merged-annotation support, and has no idea what a bean is. spring-beans builds on it to implement BeanFactory, BeanDefinition and DefaultListableBeanFactory, the machinery that creates and wires objects. spring-context wraps a bean factory with application services: events, MessageSource, Environment and profiles, and annotation configuration. spring-expression provides SpEL, which the context uses to evaluate #{...} expressions. Everything else in Spring, from AOP to MVC, is a set of beans and post-processors running on top of these four modules.

Q2L1 · BasicTricky

Is Spring Security part of the Spring Framework?

No. Spring Security is a separate project in the Spring portfolio, with its own repository, release train and version numbers, currently Spring Security 7.x alongside Spring Framework 7.x. It builds on Framework modules: spring-web for the servlet filter chain that DelegatingFilterProxy hooks into, spring-context for configuration and beans, and spring-aop for method security such as @PreAuthorize. Spring Data and Spring Integration are separate projects in the same way. Spring Boot is what aligns all these versions through its dependency BOM, which is why most teams never notice the boundary. In an interview, calling Security a Framework module is a small but telling inaccuracy, because it suggests you have never managed versions without Boot.

Q3L2 · IntermediateInternals

What is the relationship between ApplicationContext and BeanFactory architecturally?

ApplicationContext is a BeanFactory, because it extends ListableBeanFactory and HierarchicalBeanFactory, but it does not reimplement bean creation. Every standard context, such as GenericApplicationContext or AnnotationConfigApplicationContext, holds an internal DefaultListableBeanFactory and delegates getBean and all instantiation and wiring to it. What the context adds is application-level behaviour: event publication, MessageSource for internationalisation, resource pattern loading, Environment with profiles and property sources, lifecycle management, and, crucially, automatic detection and registration of BeanFactoryPostProcessors and BeanPostProcessors during refresh. So the bean factory is the engine and the context is the vehicle built around it. In practice you always use a context; a bare bean factory is only for very constrained or framework-level code.

Q4L2 · IntermediateTricky

Why does @Autowired not work with a plain DefaultListableBeanFactory?

Because @Autowired is just metadata, and nothing in DefaultListableBeanFactory reads it on its own. Annotation-driven injection is implemented by AutowiredAnnotationBeanPostProcessor, an infrastructure BeanPostProcessor that inspects each bean for @Autowired, @Value and @Inject and performs the injection. An ApplicationContext registers this processor, along with CommonAnnotationBeanPostProcessor for @PostConstruct and @Resource and ConfigurationClassPostProcessor for @Configuration, automatically during refresh. A plain bean factory registers none of them, so the annotated fields simply stay null and no error is raised. You can fix it by calling AnnotationConfigUtils.registerAnnotationConfigProcessors or adding the processor manually, but the real lesson is that every Spring annotation is inert until a processor gives it meaning.

Q5L3 · Senior EngineerInternals

How are features like @Transactional and @Cacheable plugged into the architecture?

They follow the container's standard extension recipe. An @Enable annotation, or Boot auto-configuration, imports infrastructure bean definitions: for transactions, a BeanFactoryTransactionAttributeSourceAdvisor wrapping a TransactionInterceptor, plus an auto-proxy creator, which is a BeanPostProcessor. As each bean finishes initialisation, the auto-proxy creator asks every advisor whether its pointcut matches any method of that bean, here meaning whether a method carries @Transactional. If one does, it returns a JDK or CGLIB proxy instead of the raw bean, and the proxy runs the interceptor chain around each matching call. @Cacheable, @Async and method security work identically with different advisors, which is also why all of them share the same self-invocation limitation.

Q6L3 · Senior EngineerConcept

Where is SpEL used across the Spring architecture?

SpEL appears wherever Spring needs a value or decision computed at runtime rather than fixed at compile time. In the Core Container it backs @Value("#{...}") expressions, evaluated by the context's StandardBeanExpressionResolver. Spring Security uses it for @PreAuthorize and @PostAuthorize rules such as hasRole('ADMIN') or checks against method arguments. The caching abstraction uses it for key, condition and unless attributes on @Cacheable, and @EventListener uses it for its condition attribute. Spring Integration uses it in routers, filters and header enrichers, and Spring Data supports it inside @Query strings. Parsed expressions are cached, so cost is low, but expressions are not type-checked at compile time, so test them like code.

Q7L4 · Technical ArchitectDesign

How would you structure an application so that it follows Spring's layered architecture without coupling the domain to Spring?

I would treat the domain as plain Java and push Spring to the edges. Entities, value objects and domain services carry no Spring annotations; they depend on interfaces, or ports, owned by the domain. Adapters implement those ports with Spring: controllers for inbound HTTP, Spring Data repositories or JDBC classes for persistence, and messaging listeners. All wiring lives in @Configuration classes acting as the composition root, so domain classes are created with constructors and never call new on infrastructure. Transactions and security can be declared on application services at the boundary. Finally, I would enforce the dependency direction with ArchUnit rules or Spring Modulith verification in CI, because conventions alone erode quickly.

Q8L5 · Solution ArchitectTrade-off

A team proposes adding Spring Integration to a microservice that currently uses Spring Kafka directly. How do you evaluate this?

I would start from what the service actually does. Spring for Apache Kafka already gives listener containers, retries, dead-letter publishing and KafkaTemplate, which is enough for a service that consumes one or two topics and calls domain logic. Spring Integration earns its place when the flow itself is the complexity: content-based routing, splitting and aggregating, transformations between formats, or several protocols such as Kafka, SFTP and HTTP in one pipeline, all with channel-level error handling and testable flows. It also adds a new abstraction layer, debugging cost and learning curve for the team. So I would ask for a concrete flow diagram, prototype the hardest part both ways, and document the decision in an ADR.

Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.