Spring Framework Tutorial


1. Overview

2. Spring IO Platform

3. Spring Framework

4. Environment Setup

5. Inversion of Control

6. Dependency injection

7. Spring Web MVC Framework

8. Spring Security


Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, reusable code.

October 2002 The first version was released
June 2003 The framework was first released under the Apache 2.0 license
March 2004 The first milestone release - 1.0
October 2006 Spring 2.0
November 2007 Spring 2.5
December 2009 Spring 3.0
December 2011 Spring 3.1
December 2012 Spring 3.2
December 2013 Spring 4.0


  • Spring enables developers to develop enterprise-class applications using POJOs. 
  • Spring is organized in a modular fashion. 
  • Spring does not reinvent the wheel instead, it truly makes use of some of the existing technologies. 
  • Testing an application written with Spring is simple because environment-dependent code is moved into this framework. 
  • Spring's web framework is a well-designed web MVC framework. 
  • Lightweight IoC containers tend to be lightweight, especially when compared to EJB containers. 
  • Spring provides a consistent transaction management.


SPring io platform - core

Spring Framework Provides core support for dependency injection, transaction management, web apps, data access, messaging and more.
Spring Security Protects your application with comprehensive and extensible authentication and authorization support.
Groovy Brings high-productivity dynamic language features to the JVM.
Reactor A foundation for reactive fast data applications on the JVM.

SPring io platform - Data

Spring IO addresses modern data landscape — whether it be document, graph, key-value, relational, or simply unstructured files.

SPring io platform - Workloads

Integration Channels, Adapters, Filters, Transformers

Batch Jobs, Steps, Readers, Writers

Big data Ingestion, Export, Orchestration, Hadoop

Web Controllers, REST, WebSocket


Spring is the most popular application development framework for enterprise Java.

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 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 - core container

  • The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features.
  • The Bean module provides BeanFactory which is a sophisticated implementation of the factory pattern.
  • The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured.
  • The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime.

SPring framework - data access

  • The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC related coding.
  • The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.
  • 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.

SPring framework - web

  • Spring's 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. 
  • The Web-Servlet module contains Spring's model-view-controller (MVC) implementation for web applications. Spring's MVC framework provides a clean separation between domain model code and web forms, and integrates with all the other features of the Spring Framework.
  • The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors the functionality of Web-Servlet module.
  • The  Web-Struts  module contains the support classes for integrating a classic Struts web tier within a Spring application. 

spring framework - aop

  • Spring' AOP module provides an AOP Alliance-compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated. 
  • The separate Aspects module provides integration with AspectJ.
  • The Instrumentation module provides class instrumentation support and classloader implementations to be used in certain application servers.



  • Download Eclipse from

  • Decompress downloaded file into the directory of your choice (e.g. "C:\Eclipse" on Windows)

  • ???

  • PROFIT!!!

MAVEN Integration for eclipse

  • Open Eclipse

  • Go to Help -> Eclipse Marketplace

  • Search by Maven

  • Click "Install" button at "Maven Integration for Eclipse" section

  • Follow the instruction step by step




Inversion of control (IoC) is a programming technique in which object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis. In order for the assembler to bind objects to one another, the objects must possess compatible abstractions.

  • is a concept in application development
  • "don’t call me, I’ll call you"
  • one form is Dependency Injection (DI)


Inversion Of Control

The Spring container is at the core of the Spring Framework.

The Spring container uses dependency injection (DI) to manage the components that make up an application.

The container will create the objects, wire them together, configure them, and manage their complete lifecycle from creation till destruction.

The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata provided. The configuration metadata can be represented either by XML, Java annotations, or Java code.

dependency injection containers

  • Spring BeanFactory Container

This is the simplest container providing basic support for DI. There are a number of implementations of the BeanFactory interface that come supplied straight out-of-the-box with Spring. The most commonly used BeanFactory implementation is the XmlBeanFactory class.

  • Spring ApplicationContext Container

The ApplicationContext includes all functionality of the BeanFactory, it is generally recommended over the BeanFactory. It adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.

Containers example





The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans.

A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML <bean/> definitions which you have already seen in previous chapters.

BEANS - definition

The bean definition contains the information called configuration metadata which is needed for the container to know the followings:

  • How to create a bean

  • Bean's lifecycle details

  • Bean's dependencies

beans - definition

Property Description
class* The bean class to be used to create the bean.
name The unique bean identifier.
scope The scope of the objects created from a particular bean definition.
autowiring mode Used to specify autowire mode for a bean definition
lazy-initialization mode Tells the IoC container to create a bean instance when it is first requested, rather than at startup.

beans - definition

Property Description
constructor-arg Used to inject the dependencies into the class through a class constructor
properties Used to inject the dependencies into the class through setter methods

beans - definition

Property Description
initialization method A callback to be called just after all necessary properties on the bean have been set by the container.
destruction method A callback to be used when the container containing the bean is destroyed.

BEAN definition example



BEANS - Scopes

Scope Description
singleton This scopes the bean definition to a single instance per Spring IoC container (default).
prototype This scopes a single bean definition to have any number of object instances.
request * This scopes a bean definition to an HTTP request.
session * This scopes a bean definition to an HTTP session.
global-session * This scopes a bean definition to a global HTTP session.





  • Spring Bean definition inheritance has nothing to do with Java class inheritance.

  • You can define a parent bean definition as a template and other child beans can inherit required configuration from the parent bean. 

  • A child bean definition inherits configuration data from a parent definition. The child definition can override some values, or add others, as needed. 

  • When you use XML-based configuration metadata, you indicate a child bean definition by using the parent attribute, specifying the parent bean as the value of this attribute.

Beans - inheritance example



beans - lifecycle

The life cycle of a Spring bean is easy to understand.

When a bean is instantiated, it may be required to perform some initialization to get it into a usable state.

When the bean is no longer required and is removed from the container, some cleanup may be required.

beans - lifecycle - initialization

The org.springframework.beans.factory.InitializingBean interface specifies a single method:
void afterPropertiesSet() throws Exception;

In the XML-based configuration metadata, you can use the init-method attribute to specify the name of the method that has a void no-argument signature.
<bean id="..." class="..." init-method="init"/>

Annotate the method with @PostConstruct
public void init() {

beans - lifecycle - Destruction

The  org.springframework.beans.factory.DisposableBean interface specifies a single method:
void destroy() throws Exception;

In the XML-based configuration metadata, you can use the destroy-method attribute to specify the name of the method that has a void no-argument signature.
<bean id="..." class="..." destroy-method="destroy"/>

Annotate the method with @PreDestroy
public void destroy() {

beans - Multiple lifecycle mechanisms

Multiple lifecycle mechanisms configured for the same bean are called in the following order:

  • Methods annotated with @PostConstruct

  • afterPropertiesSet() as defined by the InitializingBean callback interface

  • A custom configured init() method

  • Methods annotated with @PreDestroy

  • destroy() as defined by the DisposableBean callback interface

  • A custom configured destroy() method





When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while doing unit testing.

Dependency Injection (or sometime called wiring) helps in gluing these classes together and same time keeping them independent.


Type Description
Constructor-based Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
Setter-based Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.


Dependency Injection

Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.


Dependency Injection

Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

Dependency injection types example




Scope Description
no No autowiring. You should use explicit bean reference for wiring.
byName Autowiring by property name. Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML configuration file.
byType Autowiring by property datatype. Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file.
constructor Similar to byType, but type applies to constructor arguments.
Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire by byType.

Autowiring example



 Annotation Based Configuration

Starting from Spring 2.5 it became possible to configure the dependency injection using annotations. So instead of using XML to describe a bean wiring, you can move the bean configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

Annotation injection is performed before XML injection, thus the latter configuration will override
the former for properties wired through both approaches.

 Annotation Based Configuration

Annotation wiring is not turned on in the Spring container by default. So, before we can use annotation-based wiring, we will need to enable it in our Spring configuration file. So consider to have following configuration file in case you want to use any annotation in your Spring application.

<?xml version="1.0" encoding="UTF-8"?>
="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config/> </beans>

 Annotation Based Configuration

@Autowired The @Autowired annotation can apply to bean property setter methods, non-setter methods, constructor and properties.
@Qualifier The @Qualifier annotation along with @Autowired can be used to remove the confusion by specifiying which exact bean will be wired.
@Required The @Required annotation applies to bean property setter methods.
JSR-250 Annotations Spring supports JSR-250 based annotations which include @Resource, @PostConstruct and @PreDestroy annotations.

Java Based Configuration

Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations explained below.

Annotating a class with the @Configuration indicates that the class can be used by the Spring IoC container as a source of bean definitions.

The @Bean annotation tells Spring that a method annotated with @Bean will return an object that should be registered as a bean in the Spring application context.


Spring Web MVC Framework

The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications.

The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.

Spring Web MVC Framework

  •  The Model encapsulates the application data and in general they will consist of POJO.
  •  The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret.
  •  The Controller is responsible for processing user requests and building appropriate model and passes it to the view for rendering.

Spring Web MVC Framework

Basic Configuration


public class AppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
ServletRegistration.Dynamic dispatcher = servletContext.addServlet( "DispatcherServlet", new DispatcherServlet(context)
servletContext.addListener(new ContextLoaderListener(context));
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context =
new AnnotationConfigWebApplicationContext();
return context;



public class AppConfig {


public class WebConfig extends WebMvcConfigurerAdapter {
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
return resolver;


DispatcherServlet delegates the request to the controllers to execute the functionality specific to it.

The @Controller annotation indicates that a particular class serves the role of a controller.

The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

The class-level usage of@RequestMapping indicates that all handling methods on this controller are relative to his path. 



public class HelloController {

public String hello(ModelMap model) {
model.addAttribute("date", new Date());
return "hello";


Spring MVC supports many types of views for different presentation technologies. These include - HTML, PDF, Excel, XML, Velocity, JSON, Atom/RSS feeds, JasperReports etc. But most commonly we use JSP templates written with JSTL. 


Home page</title>
<p>Today is: ${date}</p>


URI templates can be used for convenient access to selected parts of a URL in a @RequestMapping method.

A URI Template is a URI-like string, containing one or more variable names. When you substitute values for these variables, the template becomes a URI.

For example, the URI Template http://www.example.com/users/{userId} contains the variable userId. Assigning the value fred to the variable yields http://www.example.com/users/fred.


@RequestMapping(value = "/users/{userId}", method = RequestMethod.GET)
public String findUser(@PathVariable String userId, Model model) {
    User user = userService.findById(userId);
    model.addAttribute("user", user);
    return "displayUser";

@RequestMapping(value = "/users/{userId}")
public class UsersController {
@RequestMapping(value = "/docs/{docId}", method = RequestMethod.GET) public String findDoc(@PathVariable String userId,
String docId,
Model model) { ... }


@RequestMapping(value = "/users/{userId:[a-z-]+}")
public String findUser(@PathVariable String userId, Model model) {


Matrix variables

// GET /pets/42;q=11;r=22
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET)
public void findPet(@PathVariable String petId, @MatrixVariable int q) {
  // petId == 42
  // q == 11

// GET /owners/42;q=11/pets/21;q=22
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}")
public void findPet(@MatrixVariable(value="q" pathVar="ownerId") int q1,
@MatrixVariable(value="q" pathVar="petId") int q2) { // q1 == 11 // q2 == 22 }


You can narrow the primary mapping by specifying a list of consumable media types. The request will be matched only if the Content-Type request header matches the specified media type.

@RequestMapping(value = "/pets", method = RequestMethod.POST, 
consumes = "application/json") public void addPet(@RequestBody Pet pet, Model model) { ... }


You can narrow the primary mapping by specifying a list of producible media types. The request will be matched only if the Accept request header matches one of these values. Furthermore, use of the produces condition ensures the actual content type used to generate the response respects the media types specified in the produces condition

@RequestMapping(value = "/pets/{petId}", method = RequestMethod.POST, 
produces = "application/json")
public void addPet(@PathVariable String petId, Model model) { ... }


Form handling is the day-to-day task in general web development as well as in Spring MVC development.
A typical scenario would be like this: the user fills in a web form and click Submit button.
The server receives the user’s request, validates inputs, processes some business logic and finally returns a response/message back to the user.


Hibernate is a high-performance Object/Relational persistence and query service. Hibernate ORM facilitated the storage and retrieval of Java domain objects via Object/Relational Mapping.
  • Natural Programming Model: Hibernate lets you develop persistent classes following natural Object-oriented idioms including inheritance, polymorphism, association, composition, and the Java collections framework.
  • Transparent Persistence: Hibernate requires no interfaces or base classes for persistent classes and enables any class or data structure to be persistent. 
  • High Performance: Hibernate supports lazy initialization, many fetching strategies, and optimistic locking with automatic versioning and time stamping.

hibernate advantages

  • Hibernate takes care of mapping Java classes to database tables without writing any line of code.
  • Provides simple APIs for storing and retrieving Java objects directly to and from the database.
  • Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
  • Hibernate does not require an application server to operate.
  • Manipulates complex associations of objects of your database.
  • Minimize database access with smart fetching strategies.
  • Provides Simple querying of data.

hibernate architecture


Configuration Object

The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization. It represents a configuration or properties file required by the Hibernate.

SessionFactory Object

Configuration object is used to create a SessionFactory object which inturn configures Hibernate and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.


Session Object

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. 

Transaction Object

A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality. Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA)


Query Object

Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

Criteria Object

Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

HIBERNATE And Spring mVC integration

public class PersistenceConfig {
    @Value("${jdbc.driverClassName}") private String driverClassName;
    @Value("${jdbc.url}") private String url;
    @Value("${jdbc.username}") private String username;
    @Value("${jdbc.password}") private String password;
    @Value("${hibernate.dialect}") private String hibernateDialect;
    @Value("${hibernate.show_sql}") private String hibernateShowSql;
    @Value("${hibernate.hbm2ddl.auto}") private String hibernateHbm2ddlAuto;

    .   .   .


HIBERNATE And Spring mVC integration

public Properties getHibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", hibernateDialect);
    properties.put("hibernate.show_sql", hibernateShowSql);
    properties.put("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);
    return properties;

public DataSource getDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    return dataSource;

HIBERNATE And Spring mVC integration

public LocalSessionFactoryBean getSessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setPackagesToScan(new String[]{"teach.blog.model"});
    return sessionFactory;

public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
    HibernateTransactionManager htm = new HibernateTransactionManager();
    return htm;


  • A powerful and highly customizable authentication and access-control framework
  • de-facto standard for securing Spring-based applications
  • build on top of Spring Framework


Specifically, Spring Security currently supports authentication integration with all of these technologies:

  • HTTP BASIC authentication headers (an IETF RFC-based standard)
  • HTTP Digest authentication headers (an IETF RFC-based standard)
  • HTTP X.509 client certificate exchange (an IETF RFC-based standard)
  • LDAP (a very common approach to cross-platform authentication needs, especially in large environments)
  • Form-based authentication (for simple user interface needs)
  • OpenID authentication
  • Authentication based on pre-established request headers (such as Computer Associates Siteminder)
  •  JA-SIG Central Authentication Service (otherwise known as CAS, which is a popular open source single sign-on system)
  • Transparent authentication context propagation for Remote Method Invocation (RMI) and HttpInvoker (a Spring remoting protocol)
  • Automatic "remember-me" authentication (so you can tick a box to avoid re-authentication for a predetermined period of time)
  • Anonymous authentication (allowing every unauthenticated call to automatically assume a particular security identity)
  • Run-as authentication (which is useful if one call should proceed with a different security identity)
  • Java Authentication and Authorization Service (JAAS)
  • JEE container autentication (so you can still use Container Managed Authentication if desired)
  • Kerberos
  •  Java Open Source Single Sign On (JOSSO) *
  • OpenNMS Network Management Platform *
  • AppFuse *
  • AndroMDA *
  • Mule ESB *
  • Direct Web Request (DWR) *
  •  Grails *
  • Tapestry *
  • JTrac *
  • Jasypt *
  • Roller *
  • Elastic Path *
  • Atlassian Crowd *
  • Your own authentication systems



@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    public void configureGlobal(AuthenticationManagerBuilder auth) 
throws Exception { auth.inMemoryAuthentication() .withUser("user").password("user").roles("USER") .and() .withUser("admin").password("admin").roles("USER", "ADMIN"); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().authenticated(); } }




<ul class="nav pull-right">
href="/news/add.do">Add news</a></li>

Method security

From version 2.0 onwards Spring Security has improved support substantially for adding security to your service layer methods. It provides support for JSR-250 annotation security as well as the framework's original@Secured annotation.

From 3.0 you can also make use of new expression-based annotations. ts.


@EnableGlobalMethodSecurity(securedEnabled = true)
public interface BankService {
    public Account readAccount(Long id);

    public Account post(Account account, double amount);

@EnableGlobalMethodSecurity(prePostEnabled = true)
public interface BankService {
     public Account readAccount(Long id);

     public Account post(Account account, double amount);