Spring Framework

Spring Projects

Spring Project 1


Introduction to Spring Framework

Spring Framework is a Java platform that provides comprehensive infrastructure support for developing Java applications. Spring handles the infrastructure so you can focus on your application.

Spring enables you to build applications from “plain old Java objects” (POJOs) and to apply enterprise services non- invasively to POJOs. This capability applies to the Java SE programming model and to full and partial Java EE. Spring Framework provide the facility to create high performing, easily testable, reusable code.

Learn Spring With Latest Tutorial

Spring framework is an open source Java platform and it was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003. Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.

The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make J2EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

Need of the Spring?

Spring having much of demand because of the following 3 reasons as

  1. Simplicity: Spring framework is simple because as it is non-invasive, POJO and POJI model.
  2. Testability: Writing the spring application, server [Container] is not mandatory, spring has it own container to run the applications.
  3. Loose Coupling: In spring objects are loosely coupled, this is the core concept of spring framework.
Release Version history

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 milestone release, 1.0, was released in March 2004, with further milestone releases in September 2004 and March 2005.

The Spring 1.2.6 framework won a Jolt productivity award and a JAX Innovation Award in 2006.

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.

The current version is Spring Framework 4.0, which was released in December 2013. Notable improvements in Spring 4.0 include support for Java SE 8, Groovy 2, some aspects of Java EE7, and WebSocket.


how you as an application developer can make use of the Spring platform and its advantages are:

  1. Make a Java method execute in a database transaction without having to deal with transaction APIs.
  2. Make a local Java method a remote procedure without having to deal with remote APIs.
  3. Make a local Java method a management operation without having to deal with JMX APIs.
  4. Make a local Java method a message handler without having to deal with JMS APIs.
Advantages of Spring Framework

There are many advantages of Spring Framework. They are as follows:

  1. Predefined Templates: Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies. So there is no need to write too much code. It hides the basic steps of these technologies.
  2. Loose Coupling: The Spring applications are loosely coupled because of dependency injection.
  3. Easy to test: The Dependency Injection makes easier to test the application. The EJB or Struts application require server to run the application but Spring framework doesn't require server.
  4. Lightweight: Spring framework is lightweight because of its POJO implementation. The Spring Framework doesn't force the programmer to inherit any class or implement any interface. That is why it is said non-invasive.
  5. Fast Development: The Dependency Injection feature of Spring Framework and it support to various frameworks makes the easy development of JavaEE application.
  6. Powerful abstraction: It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.
  7. Declarative support: It provides declarative support for caching, validation, transactions and formatting.
Spring Modules

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

  1. Spring Core Container: This is the base module of Spring and provides spring containers (BeanFactory and ApplicationContext).
  2. Aspect-oriented programming: Enables implementing cross-cutting concerns.
  3. Authentication and authorization: Configurable security processes that support a range of standards, protocols, tools and practices via the Spring Security sub-project (formerly Acegi Security System for Spring).
  4. Convention over configuration: A rapid application development solution for Spring-based enterprise applications is offered in the Spring Roo module.
  5. Data access: Working with relational database management systems on the Java platform using JDBC and object-relational mapping tools and with NoSQL databases.
  6. Inversion of control container: Configuration of application components and lifecycle management of Java objects, done mainly via dependency injection.
  7. Messaging: Configurative registration of message listener objects for transparent message-consumption from message queues via JMS, improvement of message sending over standard JMS APIs
  8. Model–view–controller: A HTTP- and servlet-based framework providing hooks for extension and customization for web applications and REST ful Web services.
  9. Remote access framework: Configurative RPC-style marshalling of Java objects over networks supporting RMI, CORBA and HTTP-based protocols including Web services (SOAP).
  10. Transaction management: Unifies several transaction management APIs and coordinates transactions for Java objects.
  11. Remote management: Configurative exposure and management of Java objects for local or remote configuration via JMX
  12. Testing: Support classes for writing unit tests and integration tests
Features of Spring
  1. Lightweight: spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible.
  2. Inversion of control(IOC): The basic concept of the Dependency Injection or Inversion of Control is that, programmer do not need to create the objects, instead just describe how it should be created. No need to directly connect your components and services together in program, instead just describe which services are needed by which components in a configuration file/xml file. The Spring IOC container is then responsible for binding it all up.
  3. Aspect oriented (AOP): Spring supports Aspect oriented programming. Aspect oriented programming refers to the programming paradigm which isolates secondary or supporting functions from the main program's business logic. AOP is a promising technology for separating crosscutting concerns, something usually hard to do in object-oriented programming. The application's modularity is increased in that way and its maintenance becomes significantly easier.
  4. Container: Spring contains and manages the life cycle and configuration of application objects.
  5. MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework.
  6. Transaction Management: Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments.
  7. JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS.
Core Container

The Core Container consists of the Core, Beans, Context, and Expression Language modules.

The Core and Beans modules provide the fundamental parts of the framework, including the IoC and Dependency Injection features.The BeanFactory is a sophisticated implementation of the factory pattern. It removes the need for programmatic singletons and allows you to decouple the configuration and specification of dependencies from your actual program logic.

The Context module builds on the solid base provided by the Core and Beans modules: it is a means to access objects in a framework-style manner that is similar to a JNDI registry. The Context module inherits its features from the Beans module and adds support for internationalization (using, for example, resource bundles), event-propagation, resource-loading, and the transparent creation of contexts by, for example, a servlet container. The Context module also supports Java EE features such as EJB, JMX ,and basic remoting. The ApplicationContext interface is the focal point of the Context module.

The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime. It is an extension of the unified expression language (unified EL) as specified in the JSP 2.1 specification. The language supports setting and getting property values, property assignment, method invocation, accessing the context of arrays, collections and indexers, logical and arithmetic operators, named variables, and retrieval of objects by name from Spring's IoC container. It also supports list projection and selection as well as common list aggregations.

Data Access/Integration

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules.

The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes.

The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis. Using the ORM package you can use all of these O/R-mapping frameworks in combination with all of the other features Spring offers,such as the simple declarative transaction management feature mentioned previously.

The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.

The Java Messaging Service (JMS) module contains features for producing and consuming messages.

The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs (plain old Java objects).


The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules whose detail is as follows.

The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.

  1. The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for web applications.
  2. The Web-Struts module contains the support classes for integrating a classic Struts web tier within a Spring application.
  3. The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.
Inversion of control container (dependency injection)

Central to the Spring Framework is its inversion of control (IoC) container, which provides a consistent means of configuring and managing Java objects using reflection. The container is responsible for managing object lifecycles of specific objects: creating these objects, calling their initialization methods, and configuring these objects by wiring them together

Objects created by the container are also called managed objects or beans. The container can be configured by loading XML files or detecting specific Java annotations on configuration classes. These data sources contain the bean definitions that provide the information required to create the beans

Objects can be obtained by means of either dependency lookup or dependency injection.Dependency lookup is a pattern where a caller asks the container object for an object with a specific name or of a specific type. Dependency injection is a pattern where the container passes objects by name to other objects, via either constructors, properties, or factory methods

Aspect-oriented programming framework

The Spring Framework has its own AOP framework that modularizes cross-cutting concerns in aspects. The motivation for creating a separate AOP framework comes from the belief that it would be possible to provide basic AOP features without too much complexity in either design, implementation, or configuration. The Spring AOP framework also takes full advantage of the Spring container.

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

Spring AOP has been designed to make it able to work with cross-cutting concerns inside the Spring Framework. Any object which is created and configured by the container can be enriched using Spring AOP.

The Spring Framework uses Spring AOP internally for transaction management, security, remote access, and JMX.

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

  1. schema-based approach
  2. Aspect J-based annotation style.
Data access framework

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, Hibernate, JDO, JPA, Oracle TopLink, Apache OJB, and Apache Cayenne, among others.

For all of these supported frameworks, Spring provides these feature

  1. Resource management: Automatically acquiring and releasing database resources.
  2. Exception handling: Translating data access related exception to a Spring data access hierarchy.
  3. Transaction participation: Transparent participation in ongoing transactions.
  4. Resource unwrapping: Retrieving database objects from connection pool wrappers. Abstraction for BLOB and CLOB handling.
Spring Expression Language

Spring introduces an expression language which is similar to Unified EL in its syntax but offers significantly more features. The expression language can be used when defining XML and Annotation based bean definitions and also serves as the foundation for expression language support across the Spring portfolio. Details of this new functionality can be found in the chapter Spring Expression Language (SpEL).

The Spring Expression Language was created to provide the Spring community a single, well supported expression language that can be used across all the products in the Spring portfolio. Its language features are driven by the requirements of the projects in the Spring portfolio, including tooling requirements for code completion support within the Eclipse based SpringSource Tool Suite.

Transaction management framework

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

  1. working with local and global transactions (local transaction does not require an application server)
  2. working with nested transactions
  3. working with savepoints
  4. working in almost all environments of the Java platform

In comparison, JTA only supports nested transactions and global transactions, and requires an application server (and in some cases also deployment of applications in an application server).The Spring Framework ships a PlatformTransactionManager for a number of transaction management strategies:

  1. Transactions managed on a JDBC Connection
  2. Transactions managed on Object-relational mapping Units of Work
  3. Transactions managed via the JTA TransactionManager and UserTransaction
  4. Transactions managed on other resources, like object databases.
Model-view-controller framework

The Spring Framework features its own MVC web application framework, which wasn't 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,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.

The most important interfaces defined by Spring MVC, and their responsibilities, are listed below

  1. Controller comes between Model and View to manage incoming requests and redirect to proper response. It acts as a gate that directs the incoming information. It switches between going into model or view.
  2. HandlerAdapter execution of objects that handle incoming requests
  3. HandlerInterceptor interception of incoming requests comparable, but not equal to Servlet filters (use is optional and not controlled by DispatcherServlet).
  4. HandlerMapping selecting objects that handle incoming requests (handlers) based on any attribute or condition internal or external to those requests
  5. LocaleResolver resolving and optionally saving of the locale of an individual user
  6. MultipartResolver facilitate working with file uploads by wrapping incoming requests
  7. View responsible for returning a response to the client. Some requests may go straight to view without going to the model part; others may go through all three.
  8. ViewResolver selecting a View based on a logical name for the view (use is not strictly required).
Spring beans

The Spring Beans are Java Objects that form the backbone of a Spring application. They are instantiated, assembled, and managed by the Spring IoC container. These beans are created with the configuration metadata that is supplied to the container, for example, in the form of XML definitions.

Beans defined in spring framework are singleton beans. There is an attribute in bean tag named "singleton" if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.

Bean scopes supported by Spring

There are five scoped provided by the Spring Framework supports as follows:

  1. In singleton scope, Spring scopes the bean definition to a single instance per Spring IoC container
  2. .
  3. In prototype scope, a single bean definition has any number of object instances.
  4. In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-aware Spring Application Context.
  5. In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring ApplicationContext.
  6. In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext.
  7. The default scope of a Spring Bean is Singleton.
Ways to configure a class as Spring Bean?

There are three different ways to configure Spring Bean.

  1. XML Configuration: This is the most popular configuration and we can use bean element in context file to configure a Spring Bean.
  2. Example:

    <bean name="myBean" class="com.test.spring.beans.MyBean"></bean>
  3. Java Based Configuration: If you are using only annotations, you can configure a Spring bean using @Bean annotation. This annotation is used with @Configuration classes to configure a spring bean. Sample configuration is:
  4. @Configuration
    public class MyConfiguration {
    public MyService getService(){
    return new MyService();
  5. Annotation Based Configuration: We can also use @Component, @Service, @Repository and @Controller annotations with classes to configure them to be as spring bean. For these, we would need to provide base package location to scan for these classes.