Hubbry Logo
search
logo

Spring Framework

logo
Community Hub0 Subscribers
Read side by side
from Wikipedia
Spring Framework
DeveloperVMware
Initial release1 October 2002; 23 years ago (2002-10-01)
Stable release
6.2.9[1] Edit this on Wikidata / 17 July 2025; 3 months ago (17 July 2025)
Repository
Written inJava
PlatformJava EE
TypeApplication framework
LicenseApache License 2.0
Websitespring.io/projects/spring-framework Edit this on Wikidata

The Spring Framework is an application framework and inversion of control container for the Java platform.[2] The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE (Enterprise Edition) platform. The framework does not impose any specific programming model.[citation needed]. The framework has become popular in the Java community as an addition to the Enterprise JavaBeans (EJB) model.[3] The Spring Framework is free and open source software.[4]: 121–122 [5]

Version history

[edit]
Version Date
0.9 2003
1.0 March 24, 2004
2.0 2006
3.0 2009
4.0 2013
5.0 2017
6.0 November 22, 2022
6.1 November 16, 2023
6.2 November 14, 2024

The first version was written by Rod Johnson, who released the framework with the publication of his book Expert One-on-One J2EE Design and Development in October 2002. The framework was first released under the Apache 2.0 license in June 2003. The first production release, 1.0, was released in March 2004.[6] The Spring 1.2.6 framework won a Jolt productivity award and a JAX Innovation Award in 2006.[7][8] Spring 2.0 was released in October 2006, Spring 2.5 in November 2007, Spring 3.0 in December 2009, Spring 3.1 in December 2011, and Spring 3.2.5 in November 2013.[9] Spring Framework 4.0 was released in December 2013.[10] Notable improvements in Spring 4.0 included support for Java SE (Standard Edition) 8, Groovy 2,[11][12] some aspects of Java EE 7, and WebSocket.[13]

Spring Framework 4.2.0 was released on 31 July 2015 and was immediately upgraded to version 4.2.1, which was released on 01 Sept 2015.[14] It is "compatible with Java 6, 7 and 8, with a focus on core refinements and modern web capabilities".[15]

Spring Framework 4.3 was released on 10 June 2016 and was supported until 2020.[16] It was announced to "be the final generation within the general Spring 4 system requirements (Java 6+, Servlet 2.5+), [...]".[15]

Spring 5 was built upon Reactive Streams compatible Reactor Core.[17][obsolete source]

Spring Framework 6.0 was released on 16 November 2022 and came with a Java 17+ baseline and a move to Jakarta EE 9+ (in the jakarta namespace), with a focus on the recently released Jakarta EE 10 APIs such as Servlet 6.0 and JPA 3.1.[18]

Modules

[edit]

The Spring Framework includes several modules that provide a range of services:

Spring modules are packaged as JAR files.[46] These artifacts can be accessed via the Maven Central Repository using Maven[47] or Gradle.[48]

Inversion of control container

[edit]

The inversion of control (IoC) container is the core container in the Spring Framework.[2] It provides a consistent means of configuring and managing Java objects[2][4]: 127–131  using reflection.[49] The container is responsible for managing object lifecycles of specific objects:[4]: 128  creating these objects,[50] calling their initialization methods,[49] and configuring these objects by wiring them together.[51]

In multiple cases, one need not use the container when using other parts of the Spring Framework, although using it will likely make an application easier to configure and customize. The Spring container provides a consistent mechanism to configure applications[4]: 122  and integrates with almost all Java environments, from small-scale applications to large enterprise applications.

The programmer does not directly create an object, but describes how it should be created, by defining it in the Spring configuration file. Similarly, services and components are not called directly; instead a Spring configuration file defines which services and components must be called. This IoC is intended to increase the ease of maintenance and testing.

Creating and managing beans

[edit]

Objects created by the container are called managed objects or beans.[52] The container can be configured by loading XML (Extensible Markup Language) files[50][4]: 151–152  or detecting specific Java annotations on configuration classes. These data sources contain the bean definitions that provide the information required to create the beans.

The @Configuration is a Spring-specific annotation that marks a class as the configuration class. The configuration class provides the beans to the Spring ApplicationContext.[53] Each of the methods in the Spring configuration class is configured with the @Bean annotation. The ApplicationContext interface will then return the objects configured with the @Bean annotation as beans. The advantage of Java-based configuration over XML-based configuration is better type safety and refactorability.[53]

Types of Inversion of Control

[edit]

There are several types of Inversion of Control. Dependency injection and dependency lookup are examples of Inversion of Control.[54] Objects can be obtained by means of either dependency lookup or dependency injection.[4]: 127 [55]

Dependency Injection
[edit]

Dependency injection is a pattern where the container passes objects[4]: 128  by name to other objects, via either constructors,[4]: 128  properties, or factory methods. There are several ways to implement dependency injection: constructor-based dependency injection, setter-based dependency injection and field-based dependency injection.[56]

Dependency Lookup
[edit]

Dependency lookup is a pattern where a caller asks the container object for an object with a specific name or of a specific type.

Autowiring

[edit]

The Spring framework has a feature known as autowiring, which uses the Spring container to automatically satisfy the dependencies specified in the JavaBean properties to objects of the appropriate type in the current factory.[57] This can only occur if there is only one object with the appropriate type.[57]

There are several annotations that can be used for autowiring POJOs, including the Spring-specific annotation @Autowire (as well as several other Spring-specific annotations that help resolve autowire ambiguity such as the @Qualifier or @Primary annotations),[58][59] and the standard Java annotations @Resource and @Inject.[60]

The @Qualifier annotation can be used on a class that defines a bean to inform Spring to prioritize the bean creation when autowiring it by name.[59]

The @Primary annotation can be used on a class that defines a bean to inform Spring to prioritize the bean creation when autowiring it by type.[59]

The @Resource annotation is an annotation that conforms to JSR 250, or Common Annotations for the Java Platform, and is used for autowiring references to POJOs by name.[60]

The @Inject annotation is an annotation that conforms to JSR 300, or Standard Annotations for injection, and is used for autowiring references to POJOs by type.[60]

Aspect-oriented programming framework

[edit]

The Spring Framework has its own Aspect-oriented programming (AOP) framework that modularizes cross-cutting concerns in aspects.[61] The motivation for creating a separate AOP framework is to provide basic AOP features without too much complexity in either design, implementation, or configuration. The Spring AOP framework takes full advantage of the Spring container.

The Spring AOP framework is proxy pattern-based.[62][24] It is configured at run time.[citation needed] This removes the need for a compilation step or load-time weaving.[citation needed] On the other hand, interception only allows for public method-execution on existing objects at a join point.[citation needed]

Compared to the AspectJ framework, Spring AOP is less powerful, but also less complicated.[citation needed] Spring 1.2 includes support to configure AspectJ aspects in the container. Spring 2.0 added more integration with AspectJ; for example, the pointcut language is reused and can be mixed with Spring AOP-based aspects.[citation needed] Further, Spring 2.0 added a Spring Aspects library that uses AspectJ to offer common Spring features such as declarative transaction management[62] and dependency injection via AspectJ compile-time or load-time weaving.[63] SpringSource uses AspectJ AOP in other Spring projects such as Spring Roo and Spring Insight, with Spring Security offering an AspectJ-based aspect library.[citation needed]

Spring AOP was designed to work with cross-cutting concerns inside the Spring Framework.[4]: 473  Any object which is created and configured by the container can be enriched using Spring AOP.

Since version 2.0 of the framework, Spring provides two approaches to the AOP configuration:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd">

The Spring team decided not to introduce new AOP-related terminology. Therefore, in the Spring reference documentation and API, terms such as aspect, join point, advice, pointcut, introduction, target object (advised object), AOP proxy, and weaving all have the same meanings[citation needed] as in most other AOP frameworks (particularly AspectJ).

Data access framework

[edit]

Spring's data access framework addresses common difficulties developers face when working with databases in applications. Support is provided for all popular data access frameworks in Java: JDBC, iBatis/MyBatis,[32] Hibernate,[32] Java Data Objects (JDO, discontinued since 5.x),[32] Jakarta Persistence API (JPA),[32] Oracle TopLink, Apache OJB, and Apache Cayenne, among others.

For all of these supported frameworks, Spring provides these features

  • Resource management – automatically acquiring and releasing database resources
  • Exception handling – translating data access related exception to a Spring data access hierarchy[66]
  • Transaction participation – transparent participation in ongoing transactions[4]: 290–291 
  • Resource unwrapping – retrieving database objects from connection pool wrappers
  • Abstraction for binary large object (BLOB) and character large object (CLOB) handling

All these features become available when using template classes provided by Spring for each supported framework.[67] Critics have said these template classes are intrusive and offer no advantage over using (for example) the Hibernate API directly.[68][failed verification] In response, the Spring developers have made it possible to use the Hibernate and JPA APIs directly. This however requires transparent transaction management, as application code no longer assumes the responsibility to obtain and close database resources,[69] and does not support exception translation.[70]

Together with Spring's transaction management, its data access framework offers a flexible abstraction for working with data access frameworks. The Spring Framework doesn't offer a common data access API; instead, the full power of the supported APIs is kept intact.[citation needed] The Spring Framework is the only framework available in Java that offers managed data access environments outside of an application server or container.[71][better source needed]

While using Spring for transaction management with Hibernate, the following beans may have to be configured:

  • A Datasource like com.mchange.v2.c3p0.ComboPooledDataSource or org.apache.commons.dbcp.BasicDataSource[32]
  • A SessionFactory like org.springframework.orm.hibernate3.LocalSessionFactoryBean with a DataSource attribute[72][4]: 173 
  • A HibernateProperties[4]: 173  like org.springframework.beans.factory.config.PropertiesFactoryBean
  • A TransactionManager like org.springframework.orm.hibernate3.HibernateTransactionManager with a SessionFactory attribute[72]

Other points of configuration include:

  • An AOP configuration of cutting points.
  • Transaction semantics of AOP advice[clarify].

Transaction management

[edit]

Spring's transaction management framework brings an abstraction mechanism to the Java platform.[73] Its abstraction is capable of:

In comparison, Java Transaction API (JTA) only supports nested transactions and global transactions, and requires an application server (and in some cases, deployment of applications in an application server).

The Spring Framework ships a PlatformTransactionManager[75] for a number of transaction management strategies:

  • Transactions managed on a JDBC Connection[73]
  • Transactions managed on Object-relational mapping Units of Work[73]
  • Transactions managed via the JTA[73]JtaTransactionManager[76][4]: 255–257  and UserTransaction[4]: 234 
  • Transactions managed on other resources, like object databases

Next to this abstraction mechanism the framework provides two ways of adding transaction management to applications:

  • Procedurally, by using Spring's TransactionTemplate[77]
  • Declaratively, by using metadata like XML or Java annotations (@Transactional,[62] etc.)

Together with Spring's data access framework – which integrates the transaction management framework – it is possible to set up a transactional system through configuration without having to rely on JTA or EJB. The transactional framework also integrates with messaging[78] and caching[79] engines.

Model–view–controller framework

[edit]
Spring MVC/Web Reactive presentation given by Jürgen Höller

The Spring Framework features its own model–view–controller (MVC) web application framework,[35] which was not originally planned. The Spring developers decided to write their own Web framework as a reaction to what they perceived as the poor design of the (then) popular Jakarta Struts Web framework,[80][failed verification] as well as deficiencies in other available frameworks. In particular, they felt there was insufficient separation between the presentation and request handling layers, and between the request handling layer and the model.[81]

Like Struts, Spring MVC is a request-based framework.[4]: 375  The framework defines strategy interfaces[4]: 144  for all of the responsibilities that must be handled by a modern request-based framework. The goal of each interface is to be simple and clear so that it's easy for Spring MVC users to write their own implementations, if they so choose. MVC paves the way for cleaner front end code. All interfaces are tightly coupled to the Servlet API. This tight coupling to the Servlet API is seen by some as a failure on the part of the Spring developers to offer a high level of abstraction for Web-based applications [citation needed]. However, this coupling ensures that the features of the Servlet API remain available to developers while offering a high abstraction framework to ease working with it.

The DispatcherServlet class is the front controller[82] of the framework and is responsible for delegating control to the various interfaces during the execution phases of an HTTP request.[83]

The most important interfaces defined by Spring MVC, and their responsibilities, are listed below:[84]

  • Controller: comes between Model and View to manage incoming requests and redirect to proper response.[85] Controller will map the http request to corresponding methods.[86] It acts as a gate that directs the incoming information. It switches between going into Model or View.
  • HandlerAdapter: responsible for execution of objects that handle incoming requests.[87]
  • HandlerInterceptor: responsible for intercepting incoming requests.[87] Comparable, but not equal to Servlet filters[4]: 509  (use is optional[4]: 511  and not controlled by DispatcherServlet).
  • HandlerMapping: responsible for selecting objects that handle incoming requests (handlers) based on any attribute or condition internal or external to those requests[83]
  • LocaleResolver: responsible for resolving and optionally saving of the locale of an individual user.[88]
  • MultipartResolver: facilitate working with file uploads by wrapping incoming requests.[89]
  • View: responsible for returning a response to the client. The View should not contain any business logic and should only present the data encapsulated by the Model.[35] Some requests may go straight to View without going to the Model part; others may go through all three.
  • ViewResolver: responsible for selecting a View based on a logical name for the View[90][91] (use is not strictly required[4]: 511 ).
  • Model: responsible for encapsulating business data.[90] The Model is exposed to the view by the controller.[4]: 374  (use is not strictly required).

Each strategy interface above has an important responsibility in the overall framework. The abstractions offered by these interfaces are powerful, so to allow for a set of variations in their implementations.[4]: 144  Spring MVC ships with implementations of all these interfaces and offers a feature set on top of the Servlet API. However, developers and vendors are free to write other implementations. Spring MVC uses the Java java.util.Map interface as a data-oriented abstraction for the Model where keys are expected to be String values.[citation needed]

The ease of testing the implementations of these interfaces is one important advantage of the high level of abstraction offered by Spring MVC.[92][4]: 324  DispatcherServlet is tightly coupled to the Spring inversion of control container for configuring the web layers of applications. However, web applications can use other parts of the Spring Framework, including the container, and choose not to use Spring MVC.

A workflow of Spring MVC

[edit]

When a user clicks a link or submits a form in their web-browser, the request goes to the Spring DispatcherServlet. DispatcherServlet is a front-controller in Spring MVC.[83][93] The DispatcherServlet is highly customizable and flexible.[93] Specifically, it is capable of handling more types of handlers than any implementations of org. springframework.web.servlet.mvc.Controller or org. springframework.stereotype.Controller annotated classes.[93] It consults one or more handler mappings.[83] DispatcherServlet chooses an appropriate controller and forwards the request to it. The Controller processes the particular request and generates a result. It is known as Model. This information needs to be formatted in html or any front-end technology like Jakarta Server Pages (also known as JSP)[83][94] or Thymeleaf.[94] This is the View of an application.[83] All of the information is in the Model And View object. When the controller is not coupled to a particular view, DispatcherServlet finds the actual View (such as JSP) with the help of ViewResolver.[83][4]: 390–391 

Configuration of DispatcherServlet

[edit]

As of Servlet Specification version 3.0, there are a few ways of configuring the DispatcherServlet:[95]

  • By configuring it in web.xml as shown below:[95]
<servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>MyServlet</servlet-name>
  <url-pattern>/<url-pattern>
</servlet-mapping>
  • By configuring it in web-fragment.xml[95]
  • By using javax.servlet.ServletContainerInitializer[95]
  • By implementing the org.springframework.web.WebApplicationInitializer interface.[95]
  • By using the built-in autoconfiguration for Spring Boot, which uses the SpringBootServletInitializer class.lm[95]

Remote access framework

[edit]

Spring's Remote Access framework is an abstraction for working with various RPC (remote procedure call)-based technologies available on the Java platform both for client connectivity and marshalling objects on servers.[96] The most important feature offered by this framework is to ease configuration and usage of these technologies as much as possible by combining inversion of control and AOP.

The framework provides fault-recovery (automatic reconnection after connection failure) and some optimizations for client-side use of EJB remote stateless session beans.

Spring provides support for these protocols and products out of the box

  • HTTP-based protocols
    • Hessian: binary serialization protocol,[97][4]: 335  open-sourced[4]: 335  and maintained by CORBA-based protocols[citation needed]. Hessian is maintained by the company Caucho.[4]: 335  Hessian is suitable for stateless remoting needs, in particular, Java-to-Java communication.[4]: 335–336 
    • Burlap: An XML-based binary protocol that is open-sourced and also maintained by the company Caucho.[97][4]: 335  The only advantage of using Burlap instead of Hessian is that it is XML-parsable and human readable.[4]: 335  For Java-to-Java communication, the Hessian is preferred since it is more light-weight and efficient.[4]: 335 
    • RMI (1): method invocations using RMI infrastructure yet specific to Spring[96]
    • RMI (2): method invocations using RMI interfaces complying with regular RMI usage[96]
    • RMI-IIOP (CORBA): method invocations using RMI-IIOP/CORBA
  • Enterprise JavaBean client integration[98]
    • Local EJB stateless session bean connectivity: connecting to local stateless session beans
    • Remote EJB stateless session bean connectivity: connecting to remote stateless session beans
  • SOAP

Apache CXF provides integration with the Spring Framework for RPC-style exporting of objects on the server side.[99]

Both client and server setup for all RPC-style protocols and products supported by the Spring Remote access framework (except for the Apache Axis support) is configured in the Spring Core container.

There is an alternative open-source implementation (Cluster4Spring) of a remoting subsystem included in the Spring Framework that is intended to support various schemes of remoting (1-1, 1-many, dynamic services discovering).[citation needed]

Convention-over-configuration rapid application development

[edit]

Spring Boot

[edit]

Spring Boot Extension is Spring's convention-over-configuration solution for creating stand-alone, production-grade[100] Spring-based Applications that you can "just run".[101] It is preconfigured with the Spring team's "opinionated view"[102][103] of the best configuration and use of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need little Spring configuration.[104]

Key Features:

  • Create stand-alone Spring applications
  • Embed Tomcat or Jetty[105] directly (no need to deploy WAR files)
  • Provide opinionated 'starter' Project Object Models (POMs) to simplify your Maven/Gradle configuration[106]
  • Automatically configure Spring whenever possible[107]
  • Provide production-ready[100] features such as metrics,[108] health checks[108] and externalized configuration[109]
  • Absolutely no code generation[105] and no requirement[106] for XML configuration.[110]
  • Smooth Integration and supports all Enterprise Integration Patterns.

Spring Roo

[edit]

Spring Roo is a community project which provides an alternative, code-generation based approach at using convention-over-configuration to rapidly build applications in Java. It currently supports Spring Framework, Spring Security and Spring Web Flow. Roo differs from other rapid application development frameworks by focusing on:

  • Extensibility (via add-ons)
  • Java platform productivity (as opposed to other languages)
  • Lock-in avoidance (Roo can be removed within a few minutes from any application)
  • Runtime avoidance (with associated deployment advantages)
  • Usability (particularly via the shell features and usage patterns)

Batch framework

[edit]

Spring Batch is a framework for batch processing that provides reusable functions that are essential in processing large volumes of records, including:

It provides more advanced technical services and features that enables extremely high-volume[112] and high-performance batch jobs[111] through optimizations and partitioning[111] techniques.

Spring Batch executes a series of jobs; a job consists of a number of steps and each step consists of a "READ-PROCESS-WRITE" task or single operation task (tasklet). A "single" operation task is also known as a tasklet.[113] It means doing a single task only, like cleaning up the resources before or after a step is started or completed.

The "READ-PROCESS-WRITE" process consists of these steps: "read" data from a resource (comma-separated values (CSV), XML, or database), "process" it, then "write" it to other resources (CSV, XML, or database). For example, a step may read data from a CSV file,[113] process it, and write it into the database. Spring Batch provides a number of classes to read/write CSV, XML, and database.[114]

The steps can be chained together to run as a job.[113]

Integration framework

[edit]

Spring Integration is a framework for Enterprise application integration that provides reusable functions essential to messaging or event-driven architectures.

  • routers – routes a message to a message channel based on conditions[115]
  • transformers – converts/transforms/changes the message payload and creates a new message with transformed payload[116]
  • adapters – integrates with other technologies and systems (HTTP, AMQP (Advanced Message Queuing Protocol),[117] JMS (Java Message Service), XMPP (Extensible Messaging and Presence Protocol), SMTP (Simple Mail Transfer Protocol),[118] IMAP (Internet Message Access Protocol), FTP (File Transfer Protocol) as well as FTPS/SFTP, file systems, etc.)
  • filters – filters a message based on criteria. If the criteria are not met, the message is dropped.[119]
  • service activators – invoke an operation on a service object. Spring supports the use of the annotation @ServiceActivator to declare the component that requires this functionality.[120]
  • management and auditing
  • gateways - exposes an interface to the client for the requested services. A messaging middleware is responsible for provisioning this interface. This interface decouples the messaging middleware from the client by hiding the underlying JMS or Spring Integration APIs. Gateways are related to the Facade pattern. Spring's Integration class, SimpleMessagingGateway, provides essential support for gateways. SimpleMessagingGateway enables the Spring application to specify the channel that sends requests, and the channel that expects to receive responses. The primary focus of SimpleMessagingGateway is to deal with payloads, which spares the client from the intricate details of the transmitted and received messages. SimpleMessagingGateway is used along with channels to enable integration with file systems, JMS, e-mail, or any other systems that require payloads and channels.[121]
  • splitter - Separates a large payload into smaller payloads to support different processing flows. The splitter is achieved in Spring using the splitter component. The splitter component usually forwards the messages to classes with more specialized functionality. Spring supports the @Splitter annotation to declare the component that requires this functionality.[122]
  • aggregator - Used for combining multiple messages into a single result. Loosely speaking, the aggregator is the reverse of the splitter. The aggregator publishes a single message for all components downstream. Spring supports the @Aggregator annotation to declare the component that requires this functionality.[122]

Spring Integration supports pipe-and-filter based architectures.

Spring WebSocket

[edit]

An essential rule for dealing with data streams effectively is to never block.[123] The WebSocket is a viable solution to this problem.[123] The WebSocket Protocol is a low-level transport protocol that allows full-duplex communication channels over a TCP connection. The WebSocket acts as an alternative to HTTP to enable two-way communication between the client and the server. The WebSocket is especially useful for applications that require frequent and fast exchanges of small data chunks, at a high speed and volume.[123]

Spring supports the WebSocket protocol by providing the WebSocket API for the reactive application. The @EnableWebSocket annotation gives Websocket request processing functionality when places in a Spring configuration class. A mandatory interface is the WebSocketConfigurer which grants access to the WebSocketConfigurer. Then, the Websocket URL is mapped to the relevant handlers by implementing the registerWebSocketHandlers(WebSocketHandlerRegistry) method.[124]

Spring WebFlux

[edit]

Spring WebFlux is a framework following the functional programming paradigm, designed for building reactive Spring applications. This framework uses functional programming and Reactive Streams extensively. A good use case for Spring WebFlux is for applications that require sending and receiving instantaneous information, such as a web application with chatting capabilities.[125]

Although applications using Spring WebFlux technology is usually less readable than their MVC counterparts, they are more resilient, and simpler to extend.[126] Spring WebFlux reduces the need to deal with the complications associated with synchronizing thread access.[126]

Spring WebFlux supports server-sent events (SSE), which is a server push technology that allows the client to get automatic updates from a server through an HTTP connection. This communication is unidirectional, and shares a number of similarities with the publish/subscribe model found in JMS.[123]

Relationship with Jakarta Enterprise Beans (EJB)

[edit]

The container can be turned into a partially compliant EJB (Enterprise JavaBeans) 3.0 container by means of the Pitchfork project.[citation needed] Some[who?] criticize the Spring Framework for not complying with standards.[127][failed verification] However, SpringSource doesn't see EJB 3 compliance as a major goal, and claims that the Spring Framework and the container allow for more powerful programming models.[128][failed verification]

Spring4Shell vulnerability

[edit]

A remote code execution vulnerability affecting certain versions of Spring Framework was published in April 2022 under CVE-2022-22965. It was given the name Spring4Shell in reference to the recent Log4Shell vulnerability, both having similar proofs-of-concept in which attackers could on vulnerable machines, gain shell access[129] or even full control.[130]

See also

[edit]

Citations

[edit]
  1. ^ spring-projects. "Release v6.2.9 · spring-projects/spring-framework". Retrieved 12 August 2025.
  2. ^ a b c Deinum et al. 2014, p. 47, §2 Spring Core Tasks.
  3. ^ Deinum et al. 2014, pp. 694–698, §16-2 Integrating Two Systems Using JMS.
  4. ^ a b c d e f g h i j k l m n o p q r s t u v w x y z aa ab ac ad ae Johnson & Hoeller 2004.
  5. ^ Deinum & Cosmina 2021, p. 1, §1 Setting up a Local Development Environment.
  6. ^ "Spring Framework 1.0 Final Released". Official Spring Framework blog. 24 March 2014. Retrieved 1 March 2021.
  7. ^ Jolt winners 2006
  8. ^ "JAX Innovation Award Gewinner 2006". Archived from the original on 2009-08-17. Retrieved 2009-08-12.
  9. ^ "Spring Framework 3.2.5 Released". Official Spring website. 7 Nov 2013. Retrieved 16 October 2016.
  10. ^ "Announcing Spring Framework 4.0 GA Release". Spring blog. 12 December 2013.
  11. ^ Walls 2016, pp. 92–106, §5.
  12. ^ Cosmina et al. 2017, pp. 125–126, §4 Spring Configuration in Detail and Spring Boot.
  13. ^ Cosmina et al. 2017, pp. 1–18, §1 Introducing Spring.
  14. ^ "Spring Framework 4.2 goes GA". Spring Blog. 31 July 2015.
  15. ^ a b "Spring Framework 4.2 goes GA". Spring Blog.
  16. ^ "Spring Framework Versions: Supported Versions". github.com.
  17. ^ "Reactive Spring". Spring Blog. 9 February 2016.
  18. ^ "Spring Framework 6.0 goes GA". Spring Blog. 16 November 2022.
  19. ^ Walls 2019, p. 48.
  20. ^ Spring Framework documentation for the Core Container
  21. ^ a b Johnson et al. 2005, Chapter §2 - The Bean Factory and ApplicationContext.
  22. ^ Deinum et al. 2014, p. 137, §3-1 Using Java Config to configure POJOs.
  23. ^ a b Johnson & Hoeller 2004, p. 150, Introducing the Spring Framework - The Core Bean Factory.
  24. ^ a b c d e f g Deinum & Cosmina 2021, pp. 22–25, §2 Spring Framework Fundamentals - The Spring Framework.
  25. ^ Walls 2016, p. 240, §Appendix D Spring Boot dependencies.
  26. ^ Johnson et al. 2005, Chapter §1 Introducing the Spring Framework - Module Summary.
  27. ^ Johnson et al. 2005, Chapter §4 - Spring and AOP.
  28. ^ Deinum et al. 2014, pp. 196–198, §3-17 AOP introductions for POJOs.
  29. ^ Johnson et al. 2005, Acegi Security System for Spring.
  30. ^ Deinum et al. 2014, p. 331, §7 Spring Security.
  31. ^ Walls 2019, pp. 56–59.
  32. ^ a b c d e f Deinum et al. 2014, pp. 419–426, §10 Data Access.
  33. ^ Deinum et al. 2014, pp. 677–681, §15-4 Create Message-Driven POJOs in Spring.
  34. ^ Johnson et al. 2005, Chapter §12 - Web MVC Framework.
  35. ^ a b c Deinum et al. 2014, p. 217, §4 Spring @MVC.
  36. ^ Deinum et al. 2014, pp. 525–534, §12-3 Writing a Custom ItemWriter and ItemReader.
  37. ^ Deinum et al. 2014, pp. 627–632, §14-7 Expose and Invoke Services through RMI; §14-8 Expose and Invoke Services through HTTP.
  38. ^ Deinum et al. 2014, pp. 641–658, §14-10 Introduction to contract first SOAP Web Services,§14-11 Expose and invoke SOAP Web Services with Spring-WS,§14-12 Develop SOAP Web Services with Spring-WS and XML Marshalling.
  39. ^ Johnson et al. 2005, Chapter §8 - Lightweight Remoting.
  40. ^ a b Johnson et al. 2005, Chapter §9 - Supporting Services.
  41. ^ Deinum et al. 2014, p. 475, §11 Spring Transaction Management.
  42. ^ Deinum et al. 2014, p. 591, §14 Spring Java Enterprise Services and Remoting Technologies.
  43. ^ Deinum et al. 2014, pp. 737–739, §17-3 Unit Testing Spring MVC Controllers.
  44. ^ Deinum et al. 2014, pp. 739–743, §17-4 Managing Application Contexts in Integration Tests.
  45. ^ Musib 2022, p. 358, §8.3 Introducing Spring WebFlux.
  46. ^ Cosmina et al. 2017, p. 21-23.
  47. ^ Cosmina et al. 2017, pp. 24–25, §2 Accessing Spring Modules Using Maven.
  48. ^ Cosmina et al. 2017, p. 26, §2 Accessing Spring Modules Using Gradle.
  49. ^ a b Deinum et al. 2014, pp. 53–62, §2-2 Create POJOs by Invoking a Constructor.
  50. ^ a b Deinum et al. 2014, pp. 48–52, §2-1 Manage and Configure POJOs with the Spring IoC Container.
  51. ^ Deinum et al. 2014, pp. 59–67, §2-3 Use POJO References, Auto-Wiring, and Imports to Interact with Other POJOs.
  52. ^ Deinum et al. 2014, pp. 112–116, §2-16 Use Property Editors in Spring.
  53. ^ a b Walls 2019, pp. 4–6, §1.1 Getting started with Spring - What is Spring.
  54. ^ Cosmina et al. 2017, p. 37, §3 Introducing IoC and DI in Spring.
  55. ^ What is the difference between the depencylookup and dependency injection - Spring Forum. Forum.springsource.org (2009-10-28). Retrieved on 2013-11-24.
  56. ^ Deinum & Cosmina 2021, pp. 26–32, §2 Spring Framework Fundamentals - Dependency Injection.
  57. ^ a b Johnson & Hoeller 2004, pp. 135–137, §6 Lightweight Containers and Inversion of Control - IOC Containers.
  58. ^ Deinum et al. 2014, pp. 145–151, §3-3 Use POJO References and Auto-Wiring to Interact with other POJOs.
  59. ^ a b c Cosmina et al. 2017, pp. 112–120, §3 Introducing IoC and DI in Spring - Autowiring Your Beans.
  60. ^ a b c Deinum et al. 2014, pp. 151–154, §3-4 Auto-wire POJOs the @Resource and @Inject annotation.
  61. ^ Deinum et al. 2014, pp. 99–104, §2-12 Aspect Orientated Programming.
  62. ^ a b c Deinum et al. 2014, pp. 492–494, §11-6 Managing Transactions Declaratively with the @Transactional Annotation.
  63. ^ Deinum et al. 2014, pp. 509–510, §11-11 Managing Transactions with Load-Time Weaving.
  64. ^ Spring AOP XML Configuration
  65. ^ AspectJ Annotation Configuration
  66. ^ Deinum et al. 2014, pp. 441–446, §10-5 Handling Exceptions in the Spring JDBC Framework.
  67. ^ Deinum et al. 2014, pp. 426–441, 463–465.
  68. ^ Hibernate VS Spring
  69. ^ Deinum et al. 2014, pp. 463–466, §10-8 Persisting Objects with Spring's ORM Templates.
  70. ^ Deinum et al. 2014, pp. 446–462, §10-6 Problems with Using ORM Frameworks Directly.
  71. ^ "Spring Data JPA for Abstraction of Queries". 6 February 2018. Retrieved 2018-02-06.
  72. ^ a b Deinum et al. 2014, pp. 456–460, §10-7 Configuring ORM Resource Factories in Spring.
  73. ^ a b c d Deinum et al. 2014, pp. 464–468, §11-2 Choosing a Transaction Manager Implementation.
  74. ^ a b Deinum et al. 2014, pp. 494–499, §11-7 Setting the Propagation Transaction Attribute.
  75. ^ Deinum et al. 2014, pp. 482–484, §11-2 Choosing a Transaction Manager Implementation.
  76. ^ Deinum et al. 2014, pp. 484–486, §11-3 Managing Transactions Programmatically with the Transaction Manager API.
  77. ^ Deinum et al. 2014, pp. 486–489, §11-4 Managing Transactions Programmatically with a Transaction Template.
  78. ^ Deinum et al. 2014, pp. 677–685, §15-4 Create Message-Driven POJOs in Spring.
  79. ^ Deinum et al. 2014, pp. 685–686, §15-5 Cache and pool JMS connections.
  80. ^ Introduction to the Spring Framework
  81. ^ Johnson, Expert One-on-One J2EE Design and Development, Ch. 12. et al.
  82. ^ Patterns of Enterprise Application Architecture: Front Controller
  83. ^ a b c d e f g Deinum et al. 2014, pp. 217–232, §4-1 Developing a Simple Web Application with Spring MVC.
  84. ^ Deinum & Cosmina 2021, pp. 82–83, §4 Spring MVC Architecture - The Request Processing Summary.
  85. ^ Deinum et al. 2014, pp. 217–219, §4-1 Developing a Simple Web Application with Spring MVC.
  86. ^ Walls 2019, pp. 18–19.
  87. ^ a b Deinum et al. 2014, pp. 236–239, §4-3 Intercepting Requests with Handler Interceptors.
  88. ^ Deinum et al. 2014, pp. 239–240, §4-4 Resolving User Locales.
  89. ^ Deinum & Cosmina 2021, pp. 75–76, §4 Spring MVC Architecture - Prepare a request.
  90. ^ a b Deinum et al. 2014, pp. 243–247, §4-6 Resolving Views by Names.
  91. ^ Deinum & Cosmina 2021, p. 81, §4 Spring MVC Architecture - Render a view.
  92. ^ Deinum et al. 2014, p. 723, §17 Spring Testing.
  93. ^ a b c Deinum & Cosmina 2021, pp. 73–74, §4 Spring MVC Architecture - DispatcherServlet Request Processing Workflow.
  94. ^ a b Walls 2019, p. 35.
  95. ^ a b c d e f Deinum & Cosmina 2021, pp. 84–90, §4 Spring MVC Architecture - Bootstrapping DispatcherServlet.
  96. ^ a b c Deinum et al. 2014, pp. 627–632, §14-7 Expose and Invoke Services through RMI.
  97. ^ a b Deinum et al. 2014, pp. 632–635, §14-8 Expose and Invoke Services through HTTP.
  98. ^ Deinum et al. 2014, pp. 692–694, §16-1 Integrating One System with Another Using EAI.
  99. ^ a b Deinum et al. 2014, pp. 635–641, §14-9 Expose and invoke SOAP Web Services with JAX-WS.
  100. ^ a b Walls 2016, p. vii, §foreword.
  101. ^ "Spring Boot". spring.io.
  102. ^ Walls 2016, p. 48, §2.4.
  103. ^ Deinum & Cosmina 2021, pp. 21–22, §2 Spring Framework Fundamentals.
  104. ^ Walls 2016, pp. 37–48, §2.3.
  105. ^ a b Walls 2016, p. 7, §1.1.3.
  106. ^ a b Walls 2016, p. x, §Preface.
  107. ^ Walls 2016, pp. 4–5, §1.1.2.
  108. ^ a b Walls 2016, pp. 124–139, §7.
  109. ^ Walls 2016, pp. 49–69, §3.1-§3.2.3.
  110. ^ "About Spring Boot". Retrieved 2020-03-18.
  111. ^ a b c Deinum et al. 2014, pp. 536–541, §12-7 Controlling Step Execution.
  112. ^ Deinum et al. 2014, pp. 714–717, §16-9 Staging Events Using Spring Batch.
  113. ^ a b c Deinum et al. 2014, pp. 518–524, §12-2 Reading and Writing.
  114. ^ Deinum et al. 2014, pp. 511–512, §12 Spring Batch.
  115. ^ Deinum et al. 2014, pp. 713–714, §16-8 Conditional Routing with Routers.
  116. ^ Deinum et al. 2014, pp. 704–707, §16-5 Transforming a Message from One Type to Another.
  117. ^ Deinum et al. 2014, pp. 686–690, §15-6 Send and Receive AMQP Messages with Spring.
  118. ^ Deinum et al. 2014, pp. 613–620, §14-4 Send E-mail with Spring’s E-mail Support.
  119. ^ Deinum et al. 2014, p. 406, §9-2 Using Spring in Your Servlets and Filters.
  120. ^ Deinum et al. 2014, pp. 695–698, §16-2 Integrating Two Systems Using JMS.
  121. ^ Deinum et al. 2014, pp. 717–722, §16-10 Using Gateways.
  122. ^ a b Deinum et al. 2014, pp. 710–713, §16-7 Forking Integration Control: Splitters and Aggregators.
  123. ^ a b c d Deinum & Cosmina 2021, pp. 422–425, §11 The WebSocket Protocol.
  124. ^ Deinum & Cosmina 2021, pp. 425–432, §11 The WebSocket Protocol.
  125. ^ Deinum & Cosmina 2021, p. 369, §10 Building Reactive Applications with Spring WebFlux.
  126. ^ a b Deinum & Cosmina 2021, p. 421, §11 Securing Spring WebFlux Applications.
  127. ^ Spring VS EJB3
  128. ^ "Pitchfork FAQ". Retrieved 2006-06-06.
  129. ^ "Spring4Shell: critical vulnerability in Spring - Kaspersky official blog".
  130. ^ Chirgwin, Richard (4 April 2022). "VMware sprung by Spring4shell vulnerability". itnews.com.au. Archived from the original on 13 February 2024. Retrieved 13 February 2024.

References

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
The Spring Framework is an open-source application framework for the Java platform that provides comprehensive infrastructure support for developing modern, scalable enterprise applications, emphasizing dependency injection (DI) and inversion of control (IoC) to simplify configuration and promote loose coupling.[1] Created by Rod Johnson in 2003 as a response to the perceived complexity and over-engineering of early J2EE specifications, it originated from ideas in Johnson's book Expert One-on-One J2EE Design and Development and evolved into a full framework with the release of version 1.0 in 2004.[2][3] At its core, the framework offers a lightweight container for managing application objects through DI, enabling developers to focus on business logic while handling cross-cutting concerns like transaction management, security, and data access.[4] It is modular, comprising about 20 distinct modules organized into key areas: the Core Container (including Beans, Core, Context, and Expression Language for foundational IoC and configuration); Data Access/Integration (supporting JDBC, ORM, JMS, and transaction management); Web (for servlet-based and reactive web applications); AOP and Instrumentation (for aspect-oriented programming and JVM integration); Messaging (for asynchronous communication); and Testing (for unit and integration testing).[3] This modular design allows selective use of components, making it adaptable to various deployment platforms, from traditional servers to cloud-native environments.[1] The framework's design philosophy prioritizes simplicity, testability, and non-invasiveness, promoting portable service abstractions and POJO-based development to reduce boilerplate code and vendor lock-in.[3] Over its two decades, Spring has influenced the Java ecosystem profoundly, powering projects like Spring Boot for rapid application development, Spring Security for authentication, and Spring Data for repository abstractions, and it continues to evolve with support for modern standards like Jakarta EE and reactive programming.[5] As of November 2025, the current production version is 7.0.0, requiring Java 17 or later and aligning with Jakarta EE 11 for enhanced performance and cloud readiness.[1]

History and Development

Origins and Key Contributors

The Spring Framework was founded by Rod Johnson in 2002 as a response to the perceived complexities and inefficiencies in early Java 2 Platform, Enterprise Edition (J2EE) development practices. Johnson's motivation stemmed from his experiences as a consultant, where he observed that enterprise Java applications were often overburdened by invasive specifications, particularly the heavy use of Enterprise JavaBeans (EJBs), which required extensive boilerplate code and tied business logic to container-specific implementations. This critique was detailed in his book Expert One-on-One J2EE Design and Development, published in October 2002, which advocated for simpler, more maintainable approaches using plain old Java objects (POJOs) and introducing concepts like dependency injection to decouple components and promote testability. The accompanying framework code in the book laid the groundwork for what would become Spring, aiming to streamline enterprise development by providing lightweight alternatives to J2EE standards. The initial open-source release of the Spring Framework occurred in June 2003, distributed under the Apache License 2.0 to encourage broad adoption and community contributions.[2] This early version focused on core inversion of control mechanisms and configuration management, marking a shift toward modular, non-intrusive Java application development. The framework quickly gained traction among developers seeking to avoid the verbosity of traditional J2EE while retaining its power for building robust enterprise systems. Key early contributors included Rod Johnson as the primary architect, alongside Juergen Hoeller, who joined shortly after the initial release and became instrumental in enhancing the framework's core features, such as its bean factory and configuration support. The project was initially stewarded by Interface21, a company co-founded by Johnson in 2004 to provide commercial support and services around Spring. Interface21 was renamed SpringSource in November 2007 and acquired by VMware in 2009 for $420 million, which provided resources for further professionalization while keeping the core project open-source. In 2013, SpringSource was integrated into Pivotal Software, a joint venture involving VMware, EMC, and General Electric, before returning under VMware's direct stewardship. These contributors emphasized collaborative development, with Hoeller's full-time dedication helping transform Spring from an experimental codebase into a foundational Java ecosystem tool. Following VMware's acquisition by Broadcom in November 2023, the project is now stewarded under Broadcom's portfolio.[6][7][8]

Major Releases and Evolution

The Spring Framework's evolution has been marked by a series of major releases that have progressively enhanced its capabilities, aligning with advancements in the Java ecosystem and enterprise application development needs. Each version has introduced foundational features while maintaining backward compatibility where possible, enabling widespread adoption in production environments.[1] Version 1.0, released on March 24, 2004, established the framework's core by introducing the Inversion of Control (IoC) container for dependency injection and basic Aspect-Oriented Programming (AOP) support, providing a lightweight alternative to heavy-weight J2EE specifications.[9] Spring Framework 2.0, launched on October 3, 2006, expanded configuration flexibility with XML namespaces, added annotation-based configuration to reduce boilerplate code, and integrated more deeply with AspectJ for advanced AOP capabilities.[10] The 3.0 release in December 2009 brought Java-based configuration via JavaConfig, introduced the Spring Expression Language (SpEL) for dynamic expressions, and added support for RESTful web services, facilitating more declarative and concise application setup. Version 4.0, released on December 12, 2013, provided first-class support for Java 8 features like lambdas and streams, incorporated WebSocket for real-time communication, and emphasized modularization to allow selective inclusion of components.[11] Spring 5.0, which went general availability on September 28, 2017, established Java 8 as the minimum baseline and introduced reactive programming paradigms through Spring WebFlux, enabling non-blocking, asynchronous applications built on Project Reactor.[12] In November 2022, version 6.0 marked a significant shift by migrating to Jakarta EE 9+ APIs from Java EE, and added native image support via GraalVM for faster startup times and reduced memory footprints in cloud-native deployments. The 6.2.x series, culminating in stable releases through 2025 including 6.2.12 on October 16, 2025, incorporated virtual threads from Java 21 for scalable concurrency, enhanced observability with Micrometer integrations for metrics and tracing, and served as the stable branch prior to the 7.0 release.[13][14] Version 7.0, released on November 13, 2025, focuses on API versioning for better client compatibility, enhanced concurrency support including @ConcurrencyLimit and integration with Java's virtual threads, built-in resilience patterns like retries and concurrency limits, and optimizations for Java 17 and later (recommending Java 25), including tighter integration with Jakarta EE 11. It is the current stable release as of November 2025.[15][16] Throughout its history, the framework's development has transitioned across organizational ownership: originating under Interface21 in 2004, rebranded as SpringSource in November 2007, acquired by VMware in August 2009 for $420 million, integrated into Pivotal Software in 2013, and following VMware's acquisition by Broadcom in November 2023, now stewarded under Broadcom's portfolio.[7][8]

Core Principles

Inversion of Control and Dependency Injection

Inversion of Control (IoC) is a core design principle in the Spring Framework where the framework assumes responsibility for managing the lifecycle and configuration of application objects, known as beans, thereby inverting the traditional flow of control from the application code to the container.[4] This approach promotes loose coupling by externalizing the creation and assembly of objects, allowing developers to focus on business logic rather than infrastructure concerns.[4] The Spring IoC container, implemented primarily through the BeanFactory and ApplicationContext interfaces, reads configuration metadata to instantiate, configure, and assemble beans as needed.[4] Dependency Injection (DI) represents a specific implementation of IoC in Spring, wherein dependencies between objects are provided externally by the container rather than the objects creating or locating them themselves.[17] This technique enhances modularity, testability, and maintainability by making dependencies explicit and configurable.[17] Spring supports three primary DI mechanisms: constructor injection, setter injection, and field injection. Constructor injection involves passing dependencies as arguments to a bean's constructor, ensuring that the bean is fully initialized with required dependencies upon creation and promoting immutability.[17] For example, a service class might declare a constructor parameter for a repository dependency, which the container resolves and injects during instantiation; this approach is preferred for mandatory dependencies as it prevents partial object states.[17] Setter injection, in contrast, uses setter methods to inject dependencies after the bean is instantiated, allowing for optional or reconfigurable dependencies but risking incomplete initialization if setters are not called.[17] An example would be annotating a setter method with @Autowired to wire a logger dependency. Field injection directly injects dependencies into private fields using annotations like @Autowired, bypassing getters and setters for simplicity, though it complicates testing due to hidden dependencies and is generally discouraged for production code.[17] Beans in the Spring IoC container have configurable scopes that determine their lifecycle and instance sharing. The singleton scope, the default, ensures a single shared instance per container, suitable for stateless services like DAOs. Prototype scope creates a new instance each time the bean is requested, ideal for stateful objects requiring isolation. In web applications, request scope ties an instance to the lifecycle of an HTTP request, session scope to an HTTP session, application scope to the ServletContext, and websocket scope to a WebSocket session, enabling context-specific behaviors without manual management. Spring provides multiple configuration options for defining beans and their dependencies, evolving from XML-based to more declarative approaches. XML configuration uses schema-defined elements to specify class names, dependencies, and properties, offering fine-grained control but verbosity. Annotation-based configuration leverages stereotypes like @Component, @Service, @Repository, and @Controller to mark classes for automatic detection via component scanning, with @Autowired, @Inject, or @Resource annotations handling injection points on fields, methods, or constructors. Java-based configuration, introduced as an alternative, employs @Configuration classes to define beans programmatically through @Bean methods, which return instances wired by the container, providing type safety and reduced XML reliance.[18] To manage bean lifecycles, Spring supports callbacks that allow custom initialization and cleanup logic.[19] Beans can implement the InitializingBean interface to override the afterPropertiesSet() method for post-dependency setup or the DisposableBean interface for the destroy() method on shutdown.[19] Alternatively, the JSR-250 standard annotations @PostConstruct and @PreDestroy can be placed on methods for initialization after dependency injection and cleanup before destruction, respectively, offering a portable and less intrusive option.[19] These callbacks execute in a defined order: dependency injection first, followed by @PostConstruct or afterPropertiesSet(), and symmetrically for destruction.[19]

Aspect-Oriented Programming

Aspect-oriented programming (AOP) in the Spring Framework provides a way to modularize crosscutting concerns, such as logging, security, and caching, that span multiple objects and modules, complementing object-oriented programming by separating these concerns from core business logic.[20] This approach allows developers to declare common behaviors declaratively without scattering code throughout the application, addressing limitations in traditional OOP where such concerns often lead to duplication and reduced maintainability.[21] Spring's AOP implementation focuses on method-level interception for Spring-managed beans, enabling concise and powerful aspect definitions using either schema-based configuration or annotations.[20] Core concepts in Spring AOP include aspects, which serve as modular units encapsulating crosscutting logic, typically implemented as regular classes or classes annotated with @Aspect; join points, which represent well-defined points in program execution, such as method calls or executions on Spring beans; pointcuts, which are expressions (using AspectJ's pointcut language) that match sets of join points to determine where advice applies; and advice, which defines the specific actions an aspect takes at those join points.[21] Advice comes in several types: before advice executes prior to the join point but cannot prevent its execution unless an exception is thrown; after returning advice runs only if the join point completes successfully; after throwing advice triggers on exceptions; after (finally) advice executes regardless of outcome; and around advice, the most versatile, wraps the join point to control its execution flow, including optional suppression or modification.[21] These elements work together to weave behaviors transparently around target objects. Spring AOP employs a proxy-based mechanism for weaving aspects at runtime, without requiring compile-time modifications or special class loaders.[22] By default, it uses JDK dynamic proxies for target objects that implement one or more interfaces, allowing interception of interface method calls.[23] For classes lacking interfaces, Spring falls back to CGLIB (Code Generation Library) to generate subclasses that intercept method invocations, ensuring broad compatibility while maintaining pure Java implementation.[23] This proxying approach limits Spring AOP to method execution join points on Spring beans but covers the majority of enterprise needs efficiently.[22] To extend capabilities beyond proxies, Spring integrates seamlessly with AspectJ, a full-featured AOP extension for Java, supporting annotation-driven development via annotations like @Aspect for aspect classes and @Pointcut for defining reusable pointcut expressions.[24] This style leverages AspectJ's type-safe pointcut language while relying on Spring's runtime infrastructure for weaving, without needing the AspectJ compiler.[24] For scenarios requiring broader join point support, such as field access or constructor execution, Spring enables load-time weaving (LTW), where AspectJ aspects are dynamically applied to class files as they load into the JVM, configured via Spring's LoadTimeWeaver bean and an aop.xml descriptor.[25] Common use cases for Spring AOP include applying security advice to enforce authentication and authorization on methods, caching advice to store and retrieve results transparently for performance optimization, and custom logging or monitoring advice to track application behavior without invasive changes to business code.[20] These applications demonstrate AOP's strength in handling orthogonal concerns modularly. Aspects themselves are managed as Spring beans, benefiting from dependency injection for wiring dependencies like data sources or configuration properties.[24]

Core Modules

Container and Configuration

The Spring Framework's Inversion of Control (IoC) container serves as the core runtime environment for managing application objects, known as beans, by handling their instantiation, configuration, assembly, and lifecycle.[26] It enables developers to define beans and their dependencies declaratively, promoting loose coupling and modularity in Java applications.[27] The container supports multiple configuration formats, allowing flexibility in how beans are specified and wired together.[28] At the foundation of the IoC container lies the BeanFactory interface, which provides basic functionality for bean instantiation and dependency resolution on demand.[26] BeanFactory is lightweight and suitable for resource-constrained environments, as it does not eagerly initialize singleton beans but creates them only when requested via getBean().[29] In contrast, the ApplicationContext extends BeanFactory with advanced enterprise features, including hierarchical contexts for parent-child relationships that allow bean inheritance across contexts, automatic resource loading from various sources like the classpath or file system, and built-in event publishing for application events such as context refresh or close.[26] Hierarchical contexts enable modular configurations, where child contexts can override or extend beans from parent contexts without duplication.[26] ApplicationContext also supports internationalization (i18n) through message sources and environment abstraction for profiles and properties, making it the preferred choice for most Spring applications.[30] Beans are defined within the container using various mechanisms to specify their classes, scopes, dependencies, and initialization details.[27] In XML-based configuration, beans are declared using the <bean> element, which includes attributes like id, class, scope, and depends-on to outline the bean's identity, implementation, lifecycle scope (e.g., singleton or prototype), and prerequisites.[27] For annotation-driven approaches, classes are annotated with @Component, @Service, @Repository, or @Controller, and the container scans specified packages via @ComponentScan to detect and register these as beans automatically.[31] Programmatic definition is achieved through the BeanDefinitionRegistry interface, where developers can register custom BeanDefinition objects at runtime, offering fine-grained control for dynamic or conditional bean creation. Dependency injection in the container is facilitated through autowiring, which automatically resolves and injects collaborators into beans based on predefined modes.[17] The byName mode matches dependencies by bean names against property or constructor parameter names, while byType resolves them by matching types, potentially requiring additional qualifiers if multiple candidates exist.[17] Constructor autowiring uses the bean's constructor to inject dependencies, ensuring immutability and mandatory resolution, and is the default mode for beans with a single constructor argument.[17] To resolve ambiguities in byType or constructor injection, the @Qualifier annotation specifies the exact bean name or type, overriding default matching rules for precise wiring.[28] Spring supports environment-specific configurations through profiles and property sources, allowing beans to be activated conditionally based on runtime contexts like development, testing, or production.[30] The @Profile annotation on classes or @Bean methods limits registration to active profiles, set via system properties, environment variables, or programmatically, enabling segregated configurations without code duplication.[32] Externalized properties are managed through PropertySources, which integrate placeholders like ${property.key} into bean definitions, sourcing values from files, JVM arguments, or custom providers for flexible, non-hardcoded settings.[30] For complex object creation beyond simple instantiation, the container employs FactoryBean implementations, which act as intermediaries to produce and configure objects dynamically.[27] A FactoryBean defines a getObject() method to return the actual bean instance, allowing encapsulation of creation logic such as proxy generation or resource pooling, while the container manages the FactoryBean itself as a regular bean.[33] Method injection addresses scenarios where singletons need to reference non-singleton (e.g., prototype) dependencies, using lookup methods annotated with @Lookup or XML <lookup-method> to dynamically resolve fresh instances at runtime without altering the singleton's state.[34] This technique leverages bytecode generation to override methods, ensuring thread-safe access to transient dependencies in long-lived beans.[34]

Expression Language and SpEL

The Spring Expression Language (SpEL) is a powerful expression language introduced in Spring Framework 3.0 that supports querying and manipulating object graphs at runtime.[35] Its syntax is similar to Unified EL, encompassing literals, relational operators, arithmetic operations, logical operators, and string concatenation, while offering additional capabilities such as method invocation and basic string templating.[36] SpEL enables dynamic evaluation of expressions within Spring configurations, allowing for flexible and concise definitions without extensive boilerplate code.[35] SpEL is commonly used in annotations for runtime value injection and conditional logic. The @Value annotation, for instance, supports SpEL expressions to inject values from properties, system properties, or computed results into fields, methods, or parameters.[36] Similarly, @Bean methods can incorporate SpEL for dynamic bean creation based on contextual data, such as environment variables or bean references.[35] These usages promote loose coupling by deferring value resolution until application startup or execution. Key features of SpEL include support for variables, which are referenced using the # prefix (e.g., #var), allowing access to context-specific data like root objects or custom variables set via EvaluationContext.[37] Type coercion is handled through the EvaluationContext interface, which resolves properties, methods, and fields while performing necessary conversions to match target types.[36] Collection operations are enhanced with projection (![] syntax to extract elements matching a subexpression) and selection (.?[ ] to filter collections based on criteria).[38][39] The safe navigation operator (?.) prevents NullPointerExceptions by returning null if a property or method invocation on a null object is attempted.[40] SpEL integrates seamlessly across Spring components, including bean definitions for dynamic property setting in XML or annotation-based configurations, security expressions in Spring Security for authorization rules (e.g., @PreAuthorize), and AOP pointcuts for conditional advice application.[35] In bean definitions, it supports conditional creation, such as enabling a bean only if a system property meets a threshold:
@Bean
@ConditionalOnExpression("#{systemProperties['java.version'] > '17'}")
public MyBean myBean() {
    return new MyBean();
}
This example evaluates the Java version at runtime to determine bean instantiation. Overall, SpEL's extensibility via custom resolvers and compilers enhances its utility for complex, runtime-adaptive applications.[35]

Data Access and Integration

JDBC and ORM Support

Spring's JDBC support provides abstractions that simplify database access by handling boilerplate code, resource management, and exception translation, making it easier to perform operations on relational databases.[41] The JdbcTemplate class serves as the central component for executing SQL queries, updates, and batch operations, automatically managing connections, statements, and result sets while translating JDBC-specific exceptions into Spring's unchecked DataAccessException hierarchy.[42] For instance, it offers methods like query() for retrieving data, update() for modifications, and batchUpdate() for efficient bulk inserts or updates, reducing the need for manual try-catch-finally blocks.[41] DAO support in Spring facilitates the implementation of data access objects through base classes like JdbcDaoSupport and the @Repository annotation, which enables automatic exception translation and component scanning for repositories.[43] The @Repository marker stereotype identifies classes as data access components, allowing Spring to intercept and convert vendor-specific exceptions into the portable DataAccessException types, such as DataAccessResourceFailureException or DataIntegrityViolationException.[44] Connection management is handled via DataSource configuration, which Spring obtains through dependency injection, supporting JNDI lookups for enterprise environments and integration with connection pools like HikariCP for efficient resource handling.[45] HikariCP is preferred for its performance and concurrency features, configurable as the default pooling implementation in Spring Boot but adaptable in core Spring applications.[46] For native SQL operations, NamedParameterJdbcTemplate extends JdbcTemplate to support named parameters (e.g., :name in queries), improving code readability over positional placeholders and preventing SQL injection when bound properly.[47] Similarly, SimpleJdbcInsert simplifies INSERT statements by allowing table name specification and automatic column inference from entity properties, executing via the underlying JdbcTemplate.[48] Spring's ORM support integrates with frameworks like JPA, Hibernate, and EclipseLink, providing resource management, DAO implementations, and seamless transaction participation through EntityManagerFactory and transaction managers.[49] For JPA, Spring offers JpaRepository interfaces via Spring Data JPA, which extend CrudRepository to provide methods for entity persistence, querying, and pagination, with built-in support for Hibernate and EclipseLink as providers.[50] These integrations ensure ORM operations are wrapped in Spring transactions when annotated with @Transactional, aligning with the framework's declarative transaction model.[51]

Messaging and JMS

Spring's messaging support provides abstractions for integrating Java Message Service (JMS) into applications, enabling simplified handling of asynchronous communication without direct dependency on vendor-specific APIs.[52] This framework abstracts the complexity of JMS sessions, connections, and exception handling, allowing developers to focus on business logic while supporting both point-to-point and publish-subscribe messaging patterns.[52] By leveraging Spring's dependency injection, applications can configure and inject JMS resources declaratively, promoting loose coupling and testability.[52] Central to this support is the JmsTemplate class, which facilitates synchronous sending and receiving of JMS messages.[53] It handles resource acquisition and release automatically, converting exceptions to Spring's unchecked hierarchy for consistent error management.[52] For sending, methods like convertAndSend serialize objects into JMS messages using built-in converters, such as SimpleMessageConverter for text or MappingJackson2MessageConverter for JSON payloads.[52] Receiving operations, such as receiveAndConvert, block until a message arrives and deserialize it back to domain objects, making it suitable for request-reply scenarios.[52] An example usage involves injecting JmsTemplate into a service and invoking jmsTemplate.convertAndSend("queueName", order) to dispatch an order object.[54] For asynchronous message consumption, Spring introduces message-driven Plain Old Java Objects (POJOs) via the @JmsListener annotation, introduced in Spring 4.1.[55] This annotation marks methods to automatically register as JMS listeners, with Spring managing the underlying MessageListenerContainer for thread pooling, connection recovery, and error handling.[55] Listeners can participate in transactions through container configuration, ensuring message acknowledgment aligns with application-level commits, though detailed transaction semantics are handled elsewhere.[55] Error handling is customizable via @JmsListener attributes like errorHandler or global resolvers, allowing retries or dead-letter queue routing for failed processing.[55] A typical listener might be annotated as @JmsListener(destination = "inputQueue") public void processMessage(Order order) { ... }, where the method parameter is automatically converted from the incoming JMS message.[56] Spring integrates with popular message brokers through JMS-compliant providers and dedicated projects. For Apache ActiveMQ, configuration uses JMS ConnectionFactory implementations like ActiveMQConnectionFactory, enabling embedded or remote broker setups.[57] RabbitMQ support comes via the Spring AMQP project, which provides RabbitTemplate analogous to JmsTemplate and @RabbitListener for AMQP-specific messaging, bridging non-JMS protocols. Apache Kafka integration is offered through Spring for Apache Kafka, supporting Kafka producers and consumers with KafkaTemplate for sending and @KafkaListener for reactive or batch consumption.[58] These integrations share Spring's abstraction layer, allowing applications to switch brokers with minimal code changes.[57] Connection factories are configured as Spring beans, often auto-configured in Spring Boot via properties like spring.jms.* for vendor selection and pooling.[57] For instance, an ActiveMQConnectionFactory can be defined with @Bean and properties for broker URL, username, and password, then injected into JmsTemplate or listener containers.[59] This setup ensures connections are cached and reused, with support for XA transactions where messages participate alongside other resources.[57] For more advanced messaging patterns, Spring ties into the Spring Integration module, which extends JMS support with components like message channels for decoupling producers and consumers, routers for conditional message dispatching based on headers or payloads, and transformers for modifying message content en route. These elements enable enterprise integration patterns, such as content-based routing or enrichment, while building on core JMS abstractions.[60]

Transaction and Batch Processing

Transaction Management

Spring's transaction management provides a consistent abstraction for handling transactions across various transaction APIs, including JTA, JDBC, Hibernate, and JPA, enabling both declarative and programmatic approaches to ensure data integrity in enterprise applications.[61] This abstraction simplifies transaction demarcation, exception handling, and resource synchronization without requiring an application server for basic cases.[61] By leveraging the Spring container, developers can focus on business logic while the framework manages ACID properties like atomicity, consistency, isolation, and durability.[61] Declarative transaction management in Spring primarily uses the @Transactional annotation, which declares transactional semantics on classes, methods, or interfaces and is processed via AOP proxies to intercept calls and apply transaction advice.[62] The annotation's propagation attribute controls transaction boundaries. The seven main propagation behaviors are:
  1. REQUIRED (default): "If there's already a transaction, join it; otherwise, start a new one." Most common – everything shares the same transaction.
  2. SUPPORTS: "If there's a transaction, join it; if not, run without one." Flexible for read-only or non-critical ops.
  3. MANDATORY: "You must already have a transaction, or an exception is thrown." Forces participation in an existing tx.
  4. REQUIRES_NEW: "Always start a brand-new independent transaction, even if one exists." Suspends outer tx; inner commits/rolls back separately (watch connection pools!).
  5. NOT_SUPPORTED: "Run without any transaction; suspend existing one if present." For ops that shouldn't be transactional.
  6. NEVER: "No transaction allowed; throw exception if one exists." Ensures non-transactional execution.
  7. NESTED: "Use the same physical transaction but add a savepoint for partial rollback." Allows inner rollback without killing the outer tx (JDBC savepoints).
These help manage consistency, isolation, and rollback in layered services (e.g., service calling repository).[63] The isolation attribute specifies the transaction's isolation level, such as Isolation.DEFAULT (using the database's default), READ_COMMITTED (preventing dirty reads), REPEATABLE_READ (avoiding non-repeatable reads), or SERIALIZABLE (full isolation to prevent phantom reads).[64] Rollback rules are configured via rollbackFor and noRollbackFor attributes; by default, unchecked exceptions (like RuntimeException) trigger rollback, while checked exceptions do not, but custom rules can override this based on exception types or patterns.[65] At the core of Spring's transaction infrastructure is the PlatformTransactionManager interface, which abstracts transaction coordination for specific resources.[61] For JDBC-based applications, DataSourceTransactionManager binds a JDBC Connection from a DataSource to the current thread and manages its transaction lifecycle.[61] For JPA, JpaTransactionManager integrates with a single EntityManagerFactory, handling EntityManager transactions and supporting direct JDBC access within the same transaction.[66] In contrast to declarative approaches, programmatic transaction management offers fine-grained control using the TransactionTemplate class, which simplifies demarcation through a callback mechanism that handles begin, commit, and rollback automatically.[67] Developers inject a TransactionTemplate configured with a PlatformTransactionManager and invoke its execute method with a TransactionCallback, avoiding boilerplate code compared to direct API usage like JTA.[67] This method suits scenarios requiring conditional transaction logic not easily expressed declaratively. Spring supports chained or nested transactions through propagation types like PROPAGATION_NESTED, which uses database savepoints to allow inner operations to rollback to a specific point without affecting the outer transaction.[63] Savepoints act as markers within the transaction, enabling partial rollbacks for nested calls while preserving the overall transaction integrity upon successful completion.[63] For distributed transactions spanning multiple resources, Spring integrates with JTA via JtaTransactionManager, supporting XA protocols for two-phase commit coordination.[68] Embedded transaction managers like Atomikos provide non-XA alternatives or full XA support without an external server, allowing declarative @Transactional usage across XA-compliant resources such as multiple databases.[68]

Batch Framework

Spring Batch is a lightweight, comprehensive framework within the Spring ecosystem designed to enable the development of robust batch applications for processing large volumes of data, such as ETL (Extract, Transform, Load) operations vital to enterprise systems.[69] It provides reusable functions for logging/tracing, transaction management, job processing statistics, job restart, skip, and resource management, allowing developers to focus on business logic rather than infrastructure concerns.[69] The framework follows a domain-driven design, modeling batch concepts like jobs and steps to support restartability, scalability, and fault tolerance in production environments.[70] At its core, Spring Batch organizes processing into jobs and steps, forming the foundational architecture for batch workflows. A job represents a complete batch process, composed of one or more independent steps executed sequentially or in parallel, with each step encapsulating a specific phase of data handling.[70] Steps leverage three primary interfaces to implement the read-process-write pattern: ItemReader, which reads data one item at a time from sources like files, databases, or queues, including composite readers for sequential access from multiple sources (introduced in Spring Batch 5.2); ItemProcessor, an optional component that transforms or validates individual items; and ItemWriter, which writes processed items in bulk to destinations such as databases or files.[71] This pattern promotes modularity, enabling developers to configure readers, processors, and writers as Spring beans for reuse across jobs.[71] Spring Batch primarily employs chunk-oriented processing for steps, where data is read sequentially, processed into configurable chunks, and written within transaction boundaries to ensure atomicity and consistency.[72] The chunk size determines the number of items processed per transaction—typically set to balance memory usage and performance, with a default of 1 if unspecified—and can be adjusted via the chunk() method in step configuration.[72] To enhance fault tolerance, the framework supports skip and retry policies: skips allow non-fatal exceptions to be ignored up to a configurable limit (default 10), logging the skipped items for later review, while retries enable automatic reattempts of failed items a specified number of times for transient errors, excluding fatal exceptions like data integrity violations.[73][74] These mechanisms, combined with transaction rollback on chunk failure, provide robust error handling without halting the entire job.[74] Central to job orchestration is the JobRepository, a persistence mechanism that stores metadata about job and step executions, including status, parameters, and execution history, to enable features like restart and monitoring.[75] By default, it uses JDBC to interact with relational databases via Spring's JdbcTemplate, creating tables for jobs, steps, and executions, but can be configured with JPA for object-relational mapping in environments preferring ORM-based persistence, MongoDB for NoSQL support (introduced in Spring Batch 5.2), or a resourceless in-memory implementation for testing and lightweight use cases.[75][76][77] This metadata allows jobs to resume from the last successful step upon failure, ensuring idempotency in long-running processes.[75] For scaling large-scale workloads, Spring Batch offers several techniques to distribute processing. Partitioning divides a step into sub-steps (partitions) based on data ranges or keys, executed in parallel either within a single JVM or across multiple processes, with a master step coordinating workers via the JobRepository.[78] Multi-threaded steps enable concurrent item processing within a single process using a Spring TaskExecutor, configurable with thread counts and synchronization to avoid race conditions on shared resources.[78] Remote chunking extends this by offloading chunk execution to remote workers over messaging (e.g., JMS), where the master dispatches chunks and aggregates results, ideal for distributed environments.[78] These approaches can achieve linear scalability for data-intensive tasks, limited primarily by infrastructure constraints.[78] Integrations enhance Spring Batch's usability in enterprise settings. Scheduling is achieved by combining jobs with Spring's TaskScheduler or @Scheduled annotations, triggering executions at defined intervals without replacing dedicated schedulers like Quartz.[69] The TaskExecutor integrates natively for asynchronous and multi-threaded execution within steps, providing thread pool management for performance tuning.[79] Monitoring leverages Micrometer-based metrics for job durations, item counts, and error rates, exposable via actuators for integration with tools like Prometheus, alongside JobRepository queries for execution history and listener interfaces for custom auditing.[80] Transaction boundaries in batch steps align with Spring's declarative management for commit intervals matching chunk sizes.[72]

Web and Reactive Support

Spring MVC Framework

Spring Web MVC, often referred to as Spring MVC, is the original web framework within the Spring ecosystem, built on the Jakarta Servlet API to enable the development of web applications using the Model-View-Controller (MVC) architectural pattern.[81] It provides a flexible and extensible mechanism for handling HTTP requests, processing business logic in controllers, and rendering views, all while leveraging Spring's dependency injection for managing components.[81] Since its inception with the Spring Framework, Spring MVC has been the go-to solution for traditional, servlet-based web applications, emphasizing imperative, blocking I/O operations.[81] At the core of Spring MVC is the DispatcherServlet, which acts as the front controller responsible for coordinating the entire request-response lifecycle.[81] Upon receiving an HTTP request, the DispatcherServlet consults a HandlerMapping to identify the appropriate handler (typically a controller method) based on the request's URL, HTTP method, and other attributes.[81] Once the handler is selected, a HandlerAdapter invokes the handler method, which processes the request, populates a model with data, and returns a logical view name.[81] Finally, a ViewResolver translates the logical view name into a concrete view implementation (such as JSP or Thymeleaf), which renders the response back to the client.[81] This workflow ensures loose coupling between components, allowing customization of each step through Spring's configuration. Controllers in this setup are instantiated and managed as Spring beans via the Inversion of Control (IoC) container.[81] Spring MVC supports an annotation-driven programming model, where developers use annotations to define controllers and map requests declaratively.[82] The @Controller annotation marks a class as a web controller, while @RequestMapping (or its specialized variants like @GetMapping and @PostMapping) annotates methods to handle specific HTTP requests, including support for path variables (e.g., /users/{userid} to extract userid as a method parameter), query parameters via @RequestParam, and content negotiation to select response formats based on the client's Accept header.[82] For example:
@Controller
public class UserController {
    @RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
    public String getUser(@PathVariable Long id, Model model) {
        // Retrieve user by id and add to model
        return "userProfile"; // Logical view name
    }
}
This approach simplifies configuration compared to traditional XML mappings.[82] To enable annotation-based features, Spring MVC relies on annotation-driven configuration, which can be activated via the <mvc:annotation-driven /> element in XML-based setups or the @EnableWebMvc annotation in Java-based configuration classes.[83] These mechanisms automatically register necessary components, such as RequestMappingHandlerMapping for URL-to-method mapping and RequestMappingHandlerAdapter for method invocation, while also enabling advanced features like type conversion and validation.[83] In Java configuration, @EnableWebMvc imports the DelegatingWebMvcConfiguration, which delegates to sub-configurations for MVC-specific beans.[83] Input validation in Spring MVC integrates seamlessly with the Bean Validation API (JSR-303, extended by JSR-380), allowing developers to annotate domain objects with constraints like @NotNull or @Size.[84] By applying the @Valid annotation to controller method parameters, Spring automatically triggers validation using a Validator instance, typically LocalValidatorFactoryBean, which bootstraps a JSR-303 provider like Hibernate Validator.[84] Validation errors are captured in a BindingResult object, enabling custom error handling, such as redirecting to an error view or returning error responses.[84] For instance:
@PostMapping("/users")
public String createUser(@Valid @ModelAttribute User user, BindingResult result) {
    if (result.hasErrors()) {
        return "userForm"; // Return to form with errors
    }
    // Save user
    return "redirect:/users";
}
This ensures robust data integrity without manual validation code.[84] For building RESTful web services, Spring MVC introduces @RestController, a composite annotation that combines @Controller and @ResponseBody to automatically serialize method return values directly into the HTTP response body, bypassing view resolution. This is facilitated by HttpMessageConverters, a chain of converters that handle the transformation between Java objects and HTTP payloads in formats such as JSON (via Jackson) or XML (via JAXB).[85] Developers can customize the converters by registering additional beans, ensuring support for content negotiation where the response format is determined by the request's Accept header or a path extension.[85] In Spring Boot applications, default converters are auto-configured for common formats, enhancing REST API development efficiency.[85]

Spring MVC in Simple Language

Spring MVC is a straightforward web framework inside the Spring ecosystem. It organizes your web application code using the Model-View-Controller (MVC) pattern:
  • Model: Manages the data and rules of your application.
  • View: Displays the data to the user (like HTML pages).
  • Controller: Receives user requests, works with the model, and picks the right view.
At the center is the DispatcherServlet, which acts like a smart router: it takes incoming requests and sends them to the appropriate controller for processing.

Flow of Execution (Request Lifecycle)

Spring MVC processes requests in a clear sequence:
  1. A user sends an HTTP request (e.g., visiting a URL in the browser).
  2. The request arrives at the DispatcherServlet (the central front controller).
  3. The DispatcherServlet uses HandlerMapping to find the right controller method based on the URL pattern and HTTP method (GET, POST, etc.).
  4. The HandlerAdapter calls the matching controller method.
  5. The controller executes business logic (often by calling services), prepares data in a Model object, and returns a view name (or ModelAndView).
  6. The ViewResolver converts the logical view name into an actual view resource (e.g., a Thymeleaf template or JSP file).
  7. The view renders the model data into the final output (usually HTML, but can be JSON, XML, etc.).
  8. The rendered response is sent back to the client.

Additional Code Examples

Example: RESTful API Controller with Best Practices
@RestController
@RequestMapping("/api/books")
public class BookController {

    private final BookService bookService;

    // Constructor injection (best practice)
    public BookController(BookService bookService) {
        this.bookService = bookService;
    }

    @GetMapping
    public List<BookDTO> getAllBooks() {
        return bookService.findAll();
    }

    @GetMapping("/{id}")
    public ResponseEntity<BookDTO> getBookById(@PathVariable Long id) {
        return bookService.findById(id)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<BookDTO> createBook(@Valid @RequestBody BookDTO bookDTO) {
        BookDTO created = bookService.create(bookDTO);
        return ResponseEntity.created(URI.create("/api/books/" + created.getId())).body(created);
    }
}
This shows constructor injection, DTO usage, validation, and proper ResponseEntity handling.

Real-Life Example: Online Bookstore Application

Imagine building an online bookstore:
  • List books: GET /books → BookController.list() retrieves books from database via service, adds to model, returns "books/list" view name → Thymeleaf template displays book grid.
  • View book details: GET /books/{id} → fetches single book, shows details and reviews.
  • Add book (admin): POST /books → validates form input, saves new book, redirects to list with success message.
  • REST API for mobile app: GET /api/books → returns JSON list of books.
The MVC separation keeps controllers thin (handling HTTP), services handle business rules (e.g., stock check), and repositories manage database access. This makes adding features like search, cart, or user reviews straightforward.

Best Practices

  • Prefer constructor injection over field injection for dependencies (improves testability and immutability).
  • Use @RestController instead of @Controller for REST APIs to auto-apply @ResponseBody.
  • Implement global exception handling using @ControllerAdvice and @ExceptionHandler for consistent error responses.
  • Use DTOs (Data Transfer Objects) in controllers to avoid exposing domain entities directly.
  • Always apply validation with @Valid and Bean Validation annotations (e.g., @NotBlank, @Positive).
  • Return ResponseEntity to control HTTP status codes, headers, and body precisely.
  • Organize code in layers: controllers → services → repositories.
  • Integrate Spring Security for authentication, authorization, and protection against common vulnerabilities.

Comparison with Other Frameworks

  • vs Struts 2: Spring MVC has better Spring integration, heavy use of annotations (less XML), more flexible configuration, and a much larger ecosystem/community.
  • vs Jakarta Faces (JSF): Spring MVC follows a request-response cycle (stateless by default); JSF is component-based with server-side state management, better for complex UIs but heavier and more complex for simple apps or REST.
  • vs Spring WebFlux: Spring MVC is synchronous and blocking (good for traditional web apps); WebFlux is reactive/non-blocking (scales better under high concurrency, suited for streaming and microservices).
  • vs Micronaut/Quarkus: These frameworks provide faster startup, lower memory footprint, and compile-time dependency injection; Spring MVC offers greater maturity, extensive documentation, and a vast library of extensions (e.g., Spring Data, Security, Cloud).
These additions enhance the Spring MVC section with clearer explanations, visuals, practical examples, and comparisons while preserving existing content.

Spring WebFlux and Reactive Programming

Spring WebFlux is a reactive web framework introduced in Spring Framework 5.0, designed for building non-blocking, asynchronous web applications that handle high concurrency with fewer resources.[86] It supports Reactive Streams back pressure and operates on a fully non-blocking server architecture, enabling scalable applications for scenarios like real-time data streaming and microservices.[87] Unlike traditional synchronous models, WebFlux processes requests asynchronously, allowing threads to be released back to the pool during I/O operations.[88] The reactive model in Spring WebFlux is built on Project Reactor, the default reactive library chosen for its seamless integration and support for Reactive Streams.[87] Project Reactor provides two primary types: Mono, representing an asynchronous result of 0 to 1 item, and Flux, for 0 to N items, enabling the composition of asynchronous data streams with operators for transformation, filtering, and error handling.[89] WebFlux leverages non-blocking I/O primarily through the Netty server, though it also supports Undertow and asynchronous Jakarta Servlet 5.0+ containers (such as Tomcat 10.1 and Jetty 11).[86] This setup allows applications to scale efficiently under load, as a small number of threads can manage thousands of concurrent connections without blocking.[90] As of Spring Framework 6.2, WebFlux introduces support for rendering multiple views in a single request or streaming rendered views, facilitating advanced HTML streaming use cases.[91] For defining reactive endpoints, WebFlux extends the annotation-based approach with @RestController, where controller methods can return Mono or Flux types to handle asynchronous responses.[86] For instance, a method annotated with @GetMapping might return a Mono for a single deferred value, automatically serializing it to the HTTP response body once resolved, thus avoiding thread blocking during computation or database calls.[92] This integration ensures that the entire request-response cycle remains non-blocking, with Spring automatically subscribing to the reactive types and managing back pressure.[93] WebFlux also supports injecting ServerHttpRequest as a method parameter in annotated controllers, providing low-level access to the HTTP request details. This includes accessing query parameters via the getQueryParams() method, which returns a read-only MultiValueMap<String, String> containing parsed and decoded query parameter values.[94] For example:
@GetMapping("/example")
public Mono<String> handle(ServerHttpRequest request) {
    MultiValueMap<String, String> params = request.getQueryParams();
    String value = params.getFirst("paramName");  // or params.get("paramName") for a list of values
    // process parameters reactively
    return Mono.just("Processed: " + value);
}
This approach differs from traditional Spring MVC, which relies on HttpServletRequest.getParameterMap() for query parameter access or annotations such as @RequestParam. In WebFlux, @RequestParam is also supported for convenient binding of query parameters to method arguments, similar to MVC, while ServerHttpRequest offers direct, low-level access suitable for reactive contexts.[95][96] As an alternative to annotated controllers, WebFlux offers Router Functions, a functional programming model for routing and handling requests using immutable contracts.[97] Developers define routes with RouterFunction instances, matching requests via predicates (e.g., path, method, content type) and delegating to HandlerFunction for processing, which typically returns a Mono.[97] This approach promotes composability and testability, as routes can be nested or combined declaratively, for example:
RouterFunction<ServerResponse> route = RouterFunctions.route()
    .GET("/hello", request -> ServerResponse.ok().bodyValue("Hello World!"))
    .build();
Such functions can be registered directly with the RouterFunctionMapping bean, providing a lightweight option for simple APIs without class-based controllers.[97] WebFlux includes robust support for WebSocket messaging, enhanced with STOMP (Simple Text Oriented Messaging Protocol) for structured communication over WebSockets.[98] Annotated controllers use @MessageMapping to handle incoming STOMP messages, similar to @RequestMapping in MVC, with methods processing Message<byte[]> payloads reactively via Mono or Flux.[99] For browser compatibility, SockJS provides a fallback transport layer, emulating WebSocket with polling or streaming when native support is unavailable.[100] Session management is handled through SimpMessagingTemplate for broadcasting and user-specific routing, with @SendTo or @SendToUser annotations directing responses to topics or individual sessions, ensuring reactive propagation of messages.[101] Server-sent events (SSE) in WebFlux enable one-way streaming from server to client, ideal for live updates like notifications or progress reports.[102] Endpoints return a Flux from controllers or handler functions, where each event carries data, event type, and optional ID or retry intervals, automatically formatted as text/event-stream MIME type.[97] This leverages Reactor's streaming capabilities for back-pressured, non-blocking delivery. WebFlux integrates with the RSocket protocol for binary, reactive communication, supporting request-response, request-stream, and fire-and-forget patterns over TCP or WebSocket.[103] In a WebFlux application, RSocket can be exposed via @MessageMapping in controllers or functional handlers, using RSocketRequester for outbound interactions, with payloads wrapped in Mono or Flux for full reactive interoperability.[104] This enables efficient, multiplexed messaging in distributed systems, such as between microservices.[105]

Additional Features

Remote Access and Remoting

Spring Framework facilitates remote access to services through abstractions that simplify the exposure and invocation of beans across distributed systems, primarily via synchronous remote procedure call (RPC) mechanisms. These abstractions decouple application code from underlying transport protocols, enabling developers to configure remoting declaratively using dependency injection. While earlier versions emphasized Java-specific protocols like RMI, modern usage prioritizes HTTP-based and standards-compliant approaches for interoperability. Support for Remote Method Invocation (RMI) in Spring allows services to be exposed as RMI endpoints without direct interaction with RMI registries or stubs. Developers use the RmiServiceExporter to publish a Spring bean as an RMI service and the RmiProxyFactoryBean on the client side to create a proxy for remote invocations, handling exceptions and resource management transparently. This integration leverages Java's built-in RMI infrastructure for Java-to-Java communication over TCP/IP. However, RMI support has been deprecated since Spring Framework 5.3 due to security vulnerabilities in Java serialization and lack of broader adoption, with full removal in version 6.0.[106] Hessian and Burlap provide lightweight, HTTP-based alternatives for RPC-style remoting, suitable for cross-language scenarios. Hessian employs binary serialization over HTTP for efficient data transfer, using HessianServiceExporter to expose services and HessianProxyFactoryBean for client proxies that marshal method calls into HTTP requests. Burlap, developed by Caucho Technology, offers a human-readable XML-based serialization variant with analogous classes (BurlapServiceExporter and BurlapProxyFactoryBean), trading efficiency for inspectability. Both protocols avoid the complexity of SOAP while supporting any Java interface, but like RMI, they rely on Java serialization and were deprecated in Spring 5.3 for similar security and maintenance reasons, removed in 6.0.[106] The HTTP Invoker protocol enables Java-to-Java remoting over HTTP using Spring's custom serialization format, combining the simplicity of HTTP with Java-specific optimizations. Servers configure HttpInvokerServiceExporter to handle incoming requests, while clients use HttpInvokerProxyFactoryBean to generate proxies that serialize method invocations into HTTP POST bodies. This approach supports Spring's AOP features for remote calls and integrates seamlessly with servlet containers, but it is limited to Java environments. Deprecated in Spring 5.3 and removed in 6.0, it is no longer recommended due to deserialization risks and the preference for RESTful standards.[106] For contemporary REST-based remoting, Spring provides client abstractions to consume HTTP services synchronously or reactively. The RestTemplate class, a synchronous HTTP client, simplifies REST interactions with methods like getForObject and postForEntity, supporting URI templates and automatic marshalling via HttpMessageConverter. However, it was placed in maintenance mode in Spring 5.0 and officially deprecated in 7.0, with migration encouraged to newer alternatives due to its blocking nature. The WebClient, introduced in Spring 5.0, offers a non-blocking, reactive interface built on Project Reactor, enabling fluent HTTP requests with backpressure handling and integration with Spring WebFlux for scalable remote access. In Spring 6.1, the RestClient emerged as a modern synchronous successor to RestTemplate, providing a builder-style API for concise, fluent calls while supporting the same converters and error handling. These clients facilitate remote service invocation in microservices architectures without tying to specific protocols.[107][108][109][110] Spring integrates with gRPC, a high-performance RPC framework developed by Google, through the dedicated Spring gRPC project, which provides Spring Boot auto-configuration and annotations for service implementation. Developers annotate interfaces with @GrpcService to expose them as gRPC servers, leveraging Protocol Buffers for schema definition and efficient binary serialization over HTTP/2. Client-side support includes @GrpcClient for injecting stubs, with built-in load balancing and retry mechanisms. This integration aligns gRPC with Spring's dependency injection and lifecycle management, making it suitable for polyglot microservices requiring low-latency communication. As of version 0.9.0 in 2025, it supports observability via Micrometer and is progressing toward full GA integration in Spring Boot 4.[111][112] For SOAP and broader web services, Spring supports integration with Apache CXF, an open-source framework for building RESTful and SOAP services. CXF embeds within Spring applications via XML or Java configuration, using JaxWsServerFactoryBean or annotations like @WebService to publish endpoints, while clients employ JaxWsProxyFactoryBean for dynamic proxies. The CXF Spring Boot starter automates endpoint scanning and security configuration, enabling seamless exposure of Spring beans as JAX-WS or JAX-RS services over HTTP. This combination leverages CXF's extensibility for WS-* standards while benefiting from Spring's inversion of control.[113][114]

Testing and Instrumentation

The Spring Framework provides robust support for unit and integration testing through its TestContext framework, which manages application contexts and facilitates dependency injection in test environments. This framework enables developers to load Spring contexts efficiently, apply configuration classes or XML files, and execute tests with minimal boilerplate, promoting test-driven development practices. Key annotations like @ContextConfiguration allow precise control over context initialization, supporting both full and partial loading strategies to optimize test performance.[115] For more targeted testing, Spring Boot extends these capabilities with annotations such as @SpringBootTest, which loads the complete application context for comprehensive integration tests, including auto-configuration and embedded servers where needed. In contrast, @WebMvcTest offers context slicing, focusing solely on the web layer—particularly Spring MVC components like controllers— to enable faster, isolated unit tests without loading unrelated beans. These slicing annotations reduce test execution time by limiting the scope of context bootstrapping, making them ideal for focused verification of individual layers.[116] MockMvc serves as a primary utility for testing Spring MVC controllers without starting an HTTP server, simulating requests and verifying responses within the test environment. It integrates seamlessly with the Spring Test module, allowing assertions on status codes, content types, and JSON payloads through a fluent API, thus ensuring controller logic behaves correctly under mock conditions. This approach avoids the overhead of full server spins, enhancing test speed and reliability. Instrumentation in Spring includes load-time weaving (LTW) using the AspectJ agent, which dynamically applies aspect-oriented programming (AOP) aspects to classes as they load into the JVM, without requiring compile-time modifications. Enabled via @EnableLoadTimeWeaving or JVM arguments like -javaagent, LTW is particularly useful in tests to inject cross-cutting concerns such as logging or security without altering source code, bridging Spring's proxy-based AOP with AspectJ's full weaving capabilities.[25] Spring's JMX integration, powered by the MBeanExporter, exposes managed beans (MBeans) for runtime monitoring and instrumentation, allowing external tools to query bean attributes and invoke operations. Configured declaratively, it automatically registers Spring-managed objects as JMX-compliant MBeans, supporting features like notification emission and remote access over JSR-160 connectors, which aids in diagnosing application health during development and testing.[117] Core instrumentation tools in the Spring Framework lay the groundwork for profiling, with built-in support for observability through the Observation API in recent versions, enabling the publication of metrics and traces from framework components like data access and web layers. These precursors to Spring Boot Actuator's advanced endpoints provide foundational hooks for tools like Micrometer, allowing developers to instrument custom beans for performance analysis without vendor lock-in.[118]

Ecosystem and Extensions

Spring Boot for Rapid Development

Spring Boot is an extension of the Spring Framework designed to simplify the development of production-ready applications by emphasizing convention over configuration and reducing boilerplate code. It enables developers to create stand-alone Spring-based applications that can be run using java -jar, facilitating rapid prototyping and deployment without requiring extensive XML configurations or manual setup of dependencies. A core feature of Spring Boot is its auto-configuration mechanism, which automatically configures Spring components based on the dependencies present in the application's classpath. The @EnableAutoConfiguration annotation triggers this process, where Spring Boot scans for jars and applies sensible defaults, such as setting up a data source if a database driver is detected or configuring web MVC if Spring Web is included. This approach minimizes explicit configuration while allowing overrides through properties or custom beans when needed.[119] Spring Boot further streamlines dependency management through its starters, which are predefined dependency descriptors that bundle commonly used libraries and their transitive dependencies. For instance, the spring-boot-starter-web starter includes dependencies for building web applications with Spring MVC, Tomcat as the embedded server, and other essentials like Jackson for JSON processing, all managed via a Bill of Materials (BOM) in the spring-boot-starter-parent parent POM for consistent versioning. This eliminates version conflicts and simplifies the pom.xml or build.gradle files.[120] To support easy deployment, Spring Boot integrates embedded web servers such as Tomcat (the default), Jetty, or Undertow, allowing applications to run as self-contained executable JARs without needing a separate server installation. Developers can switch servers by excluding the default and including an alternative starter, like spring-boot-starter-jetty, enabling quick testing and production deployment in containerized environments. Spring Boot Actuator provides production-ready features for monitoring and managing applications, exposing endpoints for health checks, metrics, and observability. The /actuator/health endpoint aggregates the status of application components, such as database connections or external services, reporting an overall UP, DOWN, or OUT_OF_SERVICE state. Metrics are collected via Micrometer, supporting integrations with systems like Prometheus for JVM memory usage, HTTP requests, and custom gauges, accessible at /actuator/metrics. As of November 2025, the current stable version is Spring Boot 3.5.7, aligning with Spring Framework 6.2.x or later, with support for virtual threads (introduced in version 3.2) enabling better concurrency handling in I/O-bound applications without altering code. It also includes updates for observability and dependency upgrades, such as Flyway 11.7 for database migrations.[121] Spring Boot 4.0, released in late 2025 alongside Spring Framework 7.0 (GA November 13, 2025), features robust API versioning support through URI path or header-based strategies, deeper Jakarta EE 11 integration, native image optimizations for GraalVM, built-in resilience patterns, modularization of auto-configurations, and support for Kotlin 2.2.[122][15][123]

Relationship with Jakarta EE

The Spring Framework emerged in the early 2000s as a lightweight, POJO-based alternative to the Enterprise JavaBeans (EJB) 2.x specification within Java EE (now Jakarta EE), which was criticized for its invasive nature requiring developers to implement specific interfaces, extend base classes, and use extensive deployment descriptors that tightly coupled business logic to the EJB container.[124] Introduced by Rod Johnson in his 2002 book Expert One-on-One J2EE Design and Development, Spring's first milestone release in 2004 emphasized inversion of control (IoC) and aspect-oriented programming (AOP) to simplify enterprise development without the overhead of full EJB containers.[1] This approach allowed applications to run in lightweight servlet containers like Tomcat, promoting modularity and reducing boilerplate code compared to EJB's heavyweight model.[124] In modern versions, Spring Framework 6.0 and later align closely with Jakarta EE standards, with 6.x adopting Jakarta EE 9 as the baseline API level (compatible up to Jakarta EE 10) and 7.0 (GA November 2025) adopting Jakarta EE 11, transitioning to the jakarta.* namespace for packages like Servlet, JPA, and Bean Validation.[125][126][15] This alignment enables seamless integration with Jakarta EE-compliant servers such as Tomcat 10.1 and Jetty 11, while Spring's annotations like @Transactional mirror declarative mechanisms in Jakarta EE's Contexts and Dependency Injection (CDI) for managing transactions and lifecycles.[125] Key overlaps include dependency injection, where Spring's IoC container provides functionality similar to CDI's @Inject via @Autowired or constructor injection, offering portable bean management across environments.[26] For transactions, Spring's abstraction layer supports JTA (Java Transaction API) alongside local options like JDBC, allowing declarative management without EJB-specific ties, as seen in @Transactional applying to any POJO rather than container-managed beans.[127][128] Spring also integrates natively with JPA (Jakarta Persistence API) through modules like Spring Data JPA, enabling ORM providers such as Hibernate to handle persistence in a standards-compliant manner without full Jakarta EE stack requirements.[129] Spring's design offers advantages in portability and testing ease, as its POJO-centric model avoids the full-stack compliance mandates of Jakarta EE, which require certified application servers for features like distributed transactions and security—allowing Spring applications to deploy flexibly on embedded servers or cloud-native platforms while still leveraging Jakarta EE APIs when beneficial.[124][1] This contrasts with Jakarta EE's emphasis on vendor-neutral specifications for enterprise-scale deployments, where Spring provides a more modular, non-intrusive path for developers seeking to avoid container lock-in.[130] Migration from EJB to Spring typically involves refactoring session beans into Spring-managed POJOs (using scopes like singleton or prototype), converting entity beans to standard JPA entities backed by Hibernate or another provider, and transforming message-driven beans into Spring's asynchronous messaging support via @MessageMapping or JMS listeners.[131] Spring's built-in JTA support facilitates handling distributed transactions during such transitions, often bridging to existing Jakarta EE infrastructure without full rewrites, and tools like Spring Boot Migrator can automate much of the process for legacy EJB applications.[131][132]

Security Considerations

Historical Vulnerabilities

One of the most significant historical vulnerabilities in the Spring Framework is Spring4Shell, identified as CVE-2022-22965 and disclosed in March 2022. This remote code execution (RCE) flaw affects Spring MVC and Spring WebFlux applications running on JDK 9 or later, specifically when deployed as a traditional WAR file on Apache Tomcat.[133] The vulnerability arises from the way Spring handles data binding for request parameters, allowing attackers to manipulate class loader behavior through specially crafted HTTP requests.[134] Affected versions include Spring Framework 5.3.0 through 5.3.17 and 5.2.0 through 5.2.19.[133] Exploitation of Spring4Shell involves sending a malicious POST request with parameters that exploit Tomcat's class loading mechanism, leading to arbitrary file writes on the server and potential RCE without authentication.[135] For instance, attackers could use oversized or specially named parameters to trigger the creation of temporary files in the web application's temporary directory, enabling code injection if combined with other misconfigurations.[136] This issue highlighted risks in the dynamic nature of Spring's web layer, particularly in how inversion of control (IoC) and data binding interact with server-specific features like Tomcat's resource handling. Real-world exploitation was observed shortly after disclosure, including attempts to deploy malware such as Mirai botnets.[136] Mitigation for Spring4Shell requires upgrading to Spring Framework 5.3.18 or 5.2.20 and later versions, where the data binding logic was hardened to prevent class loader manipulation.[133] Additional protections include deploying applications as Spring Boot executable JARs (which are not vulnerable), using alternative servlet containers like Jetty, and implementing strict input validation on request parameters.[133] The vulnerability underscored the importance of securing dynamic bean creation in Spring's core principles against web-layer exploits. Another notable pre-2025 vulnerability is CVE-2016-1000027, a potential RCE issue stemming from unsafe Java deserialization in the Spring Framework, particularly when using features like HttpInvokerServiceExporter for remote invocations.[137] This flaw allows attackers to execute arbitrary code if the application deserializes untrusted data and a suitable gadget chain is present in the classpath, affecting Spring Framework versions 4.0.0 through 4.2.9. It was addressed in Spring Framework 4.3.0 and later versions, with recommendations to avoid deserializing untrusted inputs altogether. Like Spring4Shell, this vulnerability exposed risks in Spring's remoting capabilities when handling external data, prompting broader adoption of secure deserialization practices.[138]

Recent Security Issues

In 2025, the Spring Framework encountered several security vulnerabilities primarily affecting its web and reactive components, highlighting ongoing challenges in handling path traversals, expression evaluations, annotation processing, and WebSocket communications. These issues were disclosed throughout the year and addressed through timely patches, underscoring the importance of regular updates in enterprise applications.[139] One notable vulnerability, CVE-2025-41242, disclosed in August 2025, involves a path traversal flaw in Spring MVC applications deployed on non-compliant Servlet containers, such as certain embedded servers that fail to properly normalize paths. This medium-severity issue (CVSS 6.5) allows attackers to access files outside the intended directory via crafted HTTP requests, potentially exposing sensitive configuration or application data. Affected versions include 6.2.0 to 6.2.9, 6.1.0 to 6.1.21, and 5.3.0 to 5.3.43.[140][141] In September 2025, CVE-2025-41243 was reported as a critical vulnerability (CVSS 9.8) in Spring Cloud Gateway Server WebFlux, enabling unauthorized modification of Spring Environment properties through malicious Spring Expression Language (SpEL) injections. This flaw arises from improper evaluation contexts in reactive routes, potentially allowing attackers to alter application behavior, such as bypassing authentication or injecting arbitrary code, leading to full unauthorized access in misconfigured gateways. It impacts Spring Cloud Gateway versions 4.1.0 to 4.1.5 and 4.0.0 to 4.0.10.[142][143] Also in September 2025, CVE-2025-41249 exposed a privilege escalation risk due to flawed annotation detection in the Spring Framework's method security mechanisms, particularly when using @EnableMethodSecurity with type hierarchies involving parameterized supertypes. This medium-severity issue (CVSS 7.5) can result in unintended access to secured methods, as annotations may not propagate correctly, allowing privilege abuse in applications relying on role-based access control. Vulnerable versions span 6.2.0 to 6.2.10, 6.1.0 to 6.1.22, and 5.3.0 to 5.3.44.[144][145] In May 2025, CVE-2025-41232 was disclosed as a medium-severity vulnerability (CVSS 6.5) in Spring Security's method security, allowing authorization bypass for annotations on private methods when @EnableMethodSecurity is used. This issue affects applications where private methods with security annotations are inadvertently exposed, potentially leading to unauthorized access. Affected versions include 6.2.0 to 6.2.5, 6.1.0 to 6.1.18, and 5.3.0 to 5.3.41.[146] In October 2025, CVE-2025-41253 was identified as a moderate-severity flaw (CVSS 6.8) in Spring Cloud Gateway Server WebFlux, where SpEL expressions could expose environment variables or system properties if the actuator endpoint is enabled and misconfigured. This vulnerability allows potential information disclosure or further exploitation in gateway setups. It affects Spring Cloud Gateway versions 4.1.6 to 4.1.7 and 4.0.11 to 4.0.12.[147] The year closed with CVE-2025-41254 in October 2025, a CSRF vulnerability in STOMP over WebSocket implementations that permits attackers to bypass session checks and send unauthorized messages without proper origin validation. Rated medium severity (CVSS 6.5), this affects real-time applications using Spring's WebSocket support, potentially enabling message spoofing or denial-of-service in collaborative environments. It targets Spring Framework versions 6.2.0 to 6.2.11, 6.1.0 to 6.1.23, and 5.3.0 to 5.3.45.[148][149] To mitigate these vulnerabilities, Spring released patches in versions 6.2.12 and later for open-source support, alongside enterprise updates for 5.3.x and 6.1.x branches, which developers should apply promptly. Best practices include enforcing strict Servlet container compliance, validating SpEL expressions in reactive components, auditing annotation hierarchies in secured applications, implementing CSRF tokens for WebSocket endpoints, and integrating regular dependency scanning tools like OWASP Dependency-Check. These measures, combined with secure configuration defaults in modern web modules, help prevent exploitation in production deployments.[14][139]

References

User Avatar
No comments yet.