Spring Framework Notes
Spring Framework Notes
References:
Pro Spring, Fourth Edition
By: Chris Schaefer; Clarence Ho; Rob Harrop
Spring Documentation
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/
Overview
● Lightweight framework for building Java applications
● Can be used to build any kind of application from standalone Java application to web
based to enterprise application.
● Modular, so one can use only the needed modules.
● Non-intrusive, domain logic does not have dependencies on the framework. Data
access has some dependencies on the framework but can be limited to the same
layer and domain logic can be delinked.
● Lets you work with PoJo's and adds the framework support non-invasively.
Overview
● Provides enterprise infrastructure services (as APIs) to POJOs without having to
deal with the plumbing code (there are many services like messaging, database
access, security, REST, MVC etc. checkout https://spring.io/projects)
● Allows class dependencies to be injected using annotations which make classes self
documenting and dependencies are explicit (more readable code)
● Enables laying out specific behaviors on the class with simple annotations like
transactions (AOP)
Overview - Evolution
● Spring 0.9
The first public release of the framework, based on the book Expert One-on-One:
J2EE Design and Development by Rod Johnson (2002)
● Spring 1.x
● Spring Core: Bean container
● Spring 2.0
● Easy XML based configuration
● JPA support
● Java 5 support
● Spring 2.5
● Introduction @Autowired
● Spring 3.0
● Spring Expression Language
● REST support
● Spring 4.x
Overview - Evolution
● Supports Java 8 (lambdas for call back etc), min JDK 6
● Servlet 3.0 spec is highly recommended and considered minimum for most of the
features. Similarly JPA 2.0 is the minimum requirement on the deployment platform.
● Support added for Java EE7 applications spec e.g. JPA 2.1, JMS 2.0 etc.
● Bean configuration now possible via Groovy DSL. This is similar to XML based
configuration but is more concise.
● There is more what wont make much sense to me as I am new to the framework.
Following link has details.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/spring-wha
ts-new.html
Overview
Overview
● Core Container
● spring-core and spring-beans
provide the dependency injection / IoC container. Allows a class to easily configure
and specify the dependencies that it needs. So that class focuses on actual logic.
● spring-context
provides access to the objects. Its used via the ApplicationContext interface.
● spring-expression
with spring-messaging.
● Web
● spring-web provides multipart file upload, initialization of IoC container from web
● Test
spring-test module provides support for unit testing using junit and testng. Allows
loading of application context. Provides mock objects for testing the code in isolation.
Refer: http://www.slideshare.net/kelapure/java-e-evsspringshootout
http://www.slideshare.net/kelapure/java-e-evsspringshootout
Spring vs J2EE (2012)
Refer: http://www.slideshare.net/reza_rahman/java-ee-and-spring-sidebyside-34320697
Maven Integration
● Maven Basics
Maven is a tool for managing the build and dependencies of a project from a single
config file. Creating a maven project gives you the basic skeleton of the project. Use
the quick start archetype.
● Archtype is a maven plugin that contains various goals like 'generate' to perform
this task of creating a project. It allows users to create projects using a standard
template.
● Maven has a huge collection of plugins, e.g. jboss-maven-plugin.
● http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
● Maven downloads the artifacts (dependencies) and maintains in local repository
● pom.xml is the file that contains the maven project information. POM stands for
project object model.
∘ modelVersion specify the version of object model. we use 4.0.0.
● Maven build lifecycle has many phases like clean, validate, compile, test, package,
integration-test, install, deploy. When a particular phase is given then maven runs all
the prior phases upto specified phase. 'site' phase generates the documentation for
the project.
● Bill of Materials (BOM) dependency allows specifying the version at one place. All
direct/transitive dependencies are automatically pulled based on the BOM version to
avoid any compatibility issues. Spring also provides a bom dependency spring-
framework-bom.
Maven Integration
● The Maven Central repository (by Apache) is used by Spring and many other open
source softwares to publish their libraries. This is the default repository that maven
automatically searches for dependencies.
● Dependency Scope
● Compile (default) – these dependencies are available all the time in compile, run
● Provided – do not add the dependency in the jar/war as its provided by the
● System – similar to provided scope but the dependency is expected on the system
run time.
● Includes bridges to direct calls from existing logging frameworks to SLF4J which in
turn would route the requests to configured logging framework. This way you can
maintain dependencies at a single place.
● Logging performance is better as it uses parameterized logging.
●
Dependency Injection
● A class should not instantiate its dependencies but rather let those be passed in via
constructor, factory method arguments or setters. This is called dependency
injection.
● Use an interface to represent a dependency so that a different implementation of
dependency can be injected.
● However these dependencies then need to be created by the caller.
● This problem is solved by the Dependency Injection Container (DIC) or Inversion of
Control (IoC container).
● The container lets you specify the way to create the dependencies and then every
one can get those by simple factory calls. Container managed objects are called
bean. In Spring you can define beans using XML, Java configuration, Annotations,
Groovy Bean Definition (4.x).
● In Spring, the ApplicationContext lets you access the dependencies or beans.
● Its called as inversion of control because instead of the class that uses
dependencies creating those, the dependencies are injected by the container into
the class.
● A container in simple terms is just a map that has a mapping of all the
dependencies/beans and the logic to create those beans. If a bean is already
created then its simply returned to the caller (singleton) otherwise a new one is
created and returned.
● Spring provides the DI container in a very non invasive way. You just need to follow
the basic Java Beans standard (getter/setter) for the dependencies.
Dependency Injection
Benefits
● More testable code
● Easy to replace dependencies with mock objects
code
● The dependent classes also become more clean
Drawbacks
● Difficult to understand if the person is not familiar with the DI concepts
Inversion of Control
Two types dependency injection and dependency look up.
● Dependency Injection (dependencies are injected, modern approach, easy)
Constructor or setter based initialization
● Dependency Lookup (components look for their dependencies, traditional approach)
Dependency pull and contextualized dependency lookup (CDL)
Inversion of Control – Dependency Pull
● Least intrusive
● There are container specific ways to mandate dependencies in this case as well
implements.
● Business interface should contain only those setters which are required by all
implementers.
● DI is better than lookup
● Simple, less code to write (no code to pull dependencies)
● Non intrusive (no need to implement any interface for dependency pull)
● Spring Bean Factory container injects the dependencies but the main method which
initializes the container needs to pull the dependencies via ApplicationContext. For
Spring MVC this is not needed and ContextLoaderListener is used.
Bean Factory
● Core DI interface
● Manages the beans, their dependencies and life cycle
● Used to access the beans from the container
● Application must create an instance of a class that implements this interface. It also
require configuration of the class along with dependency information.
● Typically a class would implement BeanDefinitionReader along with BeanFactory.
This allows class to read bean configuration and load in BeanDefinition.
● There are two bean definition readers, PropertyBeanDefinitionReader and
XMLBeanDefinitionReader.
● Every bean has a name or id or both. This is used to refer them while specifying
dependencies and also while pulling them from the BeanFactory.
● DefaultListableBeanFactory is one of the default implementation of BeanFactory
interface and can be used to access beans.
Application Context
● Extension to the BeanFactory interface. Provides additional services like transaction,
AOP, i18n, application event handling apart from accessing beans
● Need to be initialized manually in an application, for web application automatically
initialized via the ContextLoaderListener (in web.xml).Recommended way to interact
with Spring container.
● Many ways to set this up
● XML File
The xml file need to declare the namespace for beans, There are othe spring
namespaces for aop, context for Application context configuration, tx for
transaction support.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
● Annotation Based
● Gives developers a clear view of the configuration while working on the code.
component scan tag can be configured to include/exclude some specific class based
on various criteria like class type, annotation type or some custom criteria as well.
● Mixed mode
● Infrastructure can be defined in XML and the bean config/dependencies via
annotations.
Setter Injection
● Use the Property tag inside Bean tag:
<bean id="messageRenderer"
class="com.apress.prospring4.ch3.xml.StandardOutMessageRenderer">
<property name="messageProvider" ref="messageProvider"/>
</bean>
● Use the 'p' namespace and p attribute inside Bean tag
<bean id="messageRenderer"
class="com.apress.prospring4.ch3.xml.StandardOutMessageRenderer"
p:messageProvider-ref="messageProvider"/>
● Do not mix both styles (p namespace and property).
● Using annotations
● Add @Autowired annotation to the setter.
Constructor Injection
● Define constructor to accept the dependencies as arguments.
● XML based
<bean id="messageProvider"
class="com.apress.prospring4.ch3.xml.ConfigurableMessageProvider">
<constructor-arg value="Configurable message"/>
</bean>
There is a 'c' based namespace as well to define the constructor arg.
● Annotation based
Use @Autowired annotation on the constructor along with @Value for the parameter.
For example:
@Autowired
public MyConstructor(@Value(“Hello”) String value) {}
● There is a way to specify the argument value in the xml file for annotation based
configuration as well. This is better than hardcoding values in the code.
<context:component-scan base-package="com.novell.test.springxmlconfig"></context:component-scan>
<bean id="message" class="java.lang.String" c:_0="hello from annotation with xml based string
bean"></bean>
● </context>
● Constructor confusion can happen if same number of arguments are there in two
constructors. In this case the argument type must specified in the xml or annotation
style injection should be used.
● Only one constructor can be marked with @Autowired.
Injecting Parameters
● Using the 'p' name space, different types of parameters can be injected in the XML
file. Alternatively property tag can be used. Do not mix both styles. The basic types
are automatically converted appropriately.
<bean id="injectSimple" class="com.apress.prospring4.ch3.xml.InjectSimple"
p:name="Chris Schaefer" p:age="32" p:height="1.778" p:programmer="true"
p:ageInSeconds="1009843200"/>
● Spring provides @Value annotation to inject the default values.
@Value(“5.66”) //float value
● Values can be injected using SpEL as well. Spring expression language allows
access beans properties and injecting in other beans. For example:
<bean id="injectSimple" class="com.apress.prospring4.ch3.xml.InjectSimple"
p:name=”#{config.name}” p:age="#{config.age + 1}" p:height="#{config.height}"
p:programmer="#{config.programer}"
p:ageInSeconds="#{config.ageInSeconds}"/>
Here “config” is a bean which is defined in the xml file and has default values for
various properties. We have also manipulated the age by incrementing it by 1 before
injecting it. This can be also injected using annotation e.g. @Value(“#{config.age}”).
Injecting Beans
● To inject a bean into another bean using XML, use the <ref> tag:
<bean id="oracle" name="wiseworm" class="com.apress.prospring4.ch3.BookwormOracle"/>
<bean id="injectRef" class="com.apress.prospring4.ch3.xml.InjectRef">
<property name="oracle">
<ref bean="oracle"/>
</property>
</bean>
● Nesting of Application Contexts. For large projects, its needed to have separate xml
files. One can refer to beans across application contexts (both parent and child). If
the same name bean is defined in both xml files then special mechanism needs to
be used to refer to the parent bean. Also, the child application context needs to set
the parent application context explicitly by calling
setParent(parentApplicationContext).
● You can also inject collections into the beans. There are XML tags defined for set,
map, props (properties) and list. Properties only allows Strings to be used as per
Java conventions.
● For annotations, use @Resource annotation to inject collections. To externalize the
collection elements, use util namespace in the XML file
● @Autowired does not work for collection injection as it will try to inject all beans of
the collection type (Employee in case of 'List<Employee>') instead of the appropriate
<util:list> bean.
Method Injection
● If two collaborative beans have different life cycles then use Lookup method
injection. For example, the dependent bean is singleton while the dependency is
not singleton. In this case, every time a getter is called on the dependency a new
instance of dependency is given. The dependency bean scope has to be changed to
'prototype' instead of default (which is singleton).
● Spring provides a mechanism to replace the implementation of a particular bean
method with a different implementation. Use MethodReplacer interface for this. This
works using runtime byte code enhancement.
●
Bean Naming
● There are various ways to name a bean
● Use “id” attribute
● Object has limited writable state (but creating new instance is expensive, better
● This is by default disabled and not recommended. Its better to wire the
necessary dependencies of the bean explicitly in the xml or its configuration class.
Bean Inheritance
● There are times when you need to define multiple beans of the same type / interface.
The beans will have common properties, some of which individual beans might want
to customize. Typically one might copy paste the common properties across bean
definitions which is not a good idea and is difficult to maintain / error prone.
● Spring allows parent child relation between beans of similar type (same class /
interface hierarchy) in the same ApplicationContext.. Child bean will inherit
properties / constructor values from the parent and can optionally override any value
as needed.
● For this, set 'parent' property in the child bean definition appropriately.
● For example:
<bean id="inheritParent" class="com.apress.prospring4.ch3.xml.SimpleBean"
p:name="Chris Schaefer" p:age="32"/>
● Interface based
● Implement InitializingBean to be notified about bean init
● Method / XML based - avoids coupling the code with Spring framework
● Specify the method for creation and destruction in the bean configuration
● A bean can use this name while logging messages to help in debugging. This
however ties your beans to Spring framework.
ApplicationContextAware Interface
● A bean can implement this interface to get the ApplicationContext associated with it.
This interface has only one method setApplicationContext(ApplicationContext ctx)
which is called by the Spring container during initialization.
● A bean can use this context to pull other beans or register shutdown hook.
● This is typically needed for stand-alone Spring applications. For Spring MVC,
application context is automatically made available to the beans.
FactoryBean Interface
● There are times when a particular dependency cannot be instantiated using the new
operator. These dependencies cannot be managed by the IoC container.
● The FactoryBean interface comes to rescue in such situations. It can act as an
adapter between the dependency and Spring's IoC container.
● Implement this interface in an adapter class to create the dependency (with
dependency specific factory / no new operator) and make it available to other beans
using regular dependency injection provided by Spring.
● To access the FactoryBean using application context, put an ampersand (&) before
the bean name. No reason to use this in application normally.
● Similar behavior can be achieved by using <bean> element's factory-bean and
factory-method attributes.
PropertyEditor Interface
● Property editors are used to convert bean properties from String type to actual
Property type. These are part of Standard Java package java.beans.
● In BeanFactory configuration XML, all properties are defined as Strings but the
actual property value is not String. Spring uses custom property editors to convert
these values to actual property type.
● Spring has 13 custom property handlers for Date, Float, Boolean, File, Url, String,
Collection (List), InputStream, Locale, Pattern, ByteArray, Properties, Class. These
are automatically used by Spring depending on the type of property.
bean to Spring framework. Use this if you are using Spring MVC framework as that
automatically loads ApplicationContext.
Use Cases
● Using events help decouple components. If a database update component needs to
inform the caching component about the changes then one way would for database
component to call the update() API on caching component. However this would
couple database component with caching component. If tomorrow we need to
remove caching then it would require changing the update component as well.
Similarly if some other component is also interested in the database updates then
again we need to modify the database update component.
● The better approach would be to use Spring's event mechanism and let database
update component publish an update event. The caching component can register as
a listener for that event and take action.
● One can also use JMS/Messaging technology for this. However typically these are
used for long running business critical applications. Also for distributed applications
scenario these can be used.
More ApplicationContext Features
Accessing Resources
● Spring provides a Resource interface to access resources from file
system(FileSystemResource), classpath (ClassPathResource) and url
(UrlResource).
● Ctx.getResource(“classpath:test.txt”);
● Ctx.getResource(“http://www.google.com”);
● The Resource interface has many methods to get the resource information like
getDescription(), contentLength(), exists(), getInputStream(), getFileName(),
getURI(), isReadable() etc.
● Ctx.getResource(“classpath:test.txt”);
● Ctx.getResource(“http://www.google.com”);
● The Resource interface has many methods to get the resource information like
getDescription(), contentLength(), exists(), getInputStream(), getFileName(),
getURI(), isReadable() etc.
● Define all the beans in a Java configuration class by providing getters for each of the
required bean. Annotate those beans with @Bean annotation. You can also set the
properties on the bean by calling the setters appropriately in the @Bean methods.
Additional Annotations:
● @ImportResource – can be used to load another XML file containing bean
configuration. This is not recommended as one needs to look at both XML and Java
classes for bean configuration. Use one mechanism.
● @PropertySource – can be used to load a properties file in to the application
context. This goes to Environment object.
● @ComponentScan – scans the given package to identify bean classes (ones
annotated with @Service, @Component, @Repository, @Controller) similar to XML
based component scan.
Java Configuration
● @Import – can be used to import configuration from other Java configuration
classes.
● @DependsOn – to specify the other bean on which the current bean is dependent.
● For example, following groovy configuration script creates a bean named contact
from the Contact class and set the properties as well:
beans {
contact (Contact, firstName : 'Tom', lastName: 'Jerry')
}
● Groovy configuration is very powerful. You can create the application context as well
in the configuration script. Also setup profiles, properties.
Profiles
● Can be used when one needs different set of beans based on the environment.
● For example, we have two implementations of Search interface, one for local search
and other for cloud search.
● Define two XML configuration files defining beans separately using local search
impelmentation and cloud search implementation. Set the profile attribute in the
beans element to local and cloud depending on the xml.
● When running the program pass the active profile name by the JVM argument
-Dspring.profiles.active=local or cloud.
● Same is possible via Java configuration. Define two separate Java configuration
classes and use @Profile annotation.
● Its possible to mark the active profile using the
applicationContext.getEnvironment().setActiveProfiles(“local / cloud”) as well.
● Developers can use it to define separate profiles for different run time environments.
For example, “dev” and “production”.
● The draw back is that the run time environment for all profiles need to be packaged
and can increase the size of application.
Environment & PropertySource
● Spring while configuring the ApplicationContext also configures the Environment for
the application.
● By default, the order is to search application properties in the end but this can be
changed via the Environment object obtained through
applicationContext.getEnvironment().
● Typically, an application wont directly use the Environment object but can use
property place holders in the XML configuration file like ${user.home}. To set this up,
need to define the <property-placeholder> for the context in the XML configuration
along with the path to the application property file.
● @Named – defines a injectable bean / component (also used to refer to a bean with
@Inject)
● @Inject – defines a particular (@Named) bean should be injected on the annotated
method / property
● @Singleton – marks a bean as singleton. By default the scope is prototype in JEE.
● Spring annotations are more feature rich and powerful, here are few differences:
● The @Autowired annotation can be marked with required to mark dependency
● JEE has only two bean scopes singleton and non-singleton. While Spring has
additional scopes like request (create separate bean instance for each request)
which are useful in web applications.
Spring MVC
Setting up tools
● Install JDK, setup JAVA_HOME and PATH
● Install Maven, setup M2_HOME, M2 (path to mvn command) and PATH
● Install Tomcat, use JDK path during installation
● In Eclipse/STS, link JDK (during install), Maven (Windows->Preferences->Maven)
and Tomcat (Windows->Preferences->Server)
MVC
● Commonly used pattern for presentation layer. Supported by Spring MVC, Struts etc.
● Model – represents application state (specific to user session)
● View – representation of model, user interface
● Controller – gets the user action, interacts with service layer and updates the model.
Selects the appropriate view as a response. For AJAX based clients, it can return
JSON / XML (instead of view) to allow partial updates. Its important to know that the
response (rendered view) is also returned by dispatcher servlet.
Spring MVC
● Most web frameworks have a dispatcher servlet which receives all requests and
triggers appropriate controller
● Spring MVC also has a DispatcherServlet. Each DispatcherServlet has a
corresponding WebApplicationContext that specifies servlet level controllers, view
resolving, i18n, theming etc. There can be multiple dispatcher servlets.
● There is also a root WebApplicationContext which represents application level
configuration.
● Filter is applied to every
●
request.
Common services are
defined for each
Spring MVC
webapplicationcontext
and applied to every
request like i18n,
theming, file upload.
● Handlers are methods for
particular HTTP request.
Annotated with
@RequestMapping.
● Handler Interceptors are
invoked before handlers.
Can check common logic
like only allow invoking
handlers during office
hours.
● Exception handlers are
methods annotated with
@ExceptionHandler to
handle specific
exceptions. Used in
mobile server e.g. auth
exception..
● View Resolvers pick
appropriate view based
on controller response.
Spring MVC - Configuration
Configuration
● Configure web deployment descriptor (web.xml)
● Setup root web application context (path to root xml file)
server as well
● HiddenHttpMethodFilter – allow HTTP requests other than GET/POST.
● Setup application's dispatcher servlet and specify web application context (servlet-
context.xml typical name). If you use the default naming format e.g. <dispatcher
servlet name>-servlet.xml and keep in WEB-INF/ folder then its automatically
picked up. All beans are defined here along with enabling annotation based
configuration.
● Define Spring's ContextLoaderListener for bootstrap & shutdown of root web
application context
● However you can still use Spring Boot and configure it generate traditional war files
without embedded web server. Remove the spring boot build plugin from pom.xml
and change package type to war.
● Spring Boot actuator enables many endpoints for monitoring the application like
thread dump, bean information, metrics.
● There are third party metrics libraries which can be plugged in (like coda hale
metricsl)
● You can even SSH to the application and monitor it. Running thread information.
● You can also enable TLS on the Spring Boot embedded server easily. Need to define
a bean for EmbeddedServletContainerCustomizer.
Spring MVC Basics
● The dispatcher servlet invokes the appropriate request handler based on the
@RequestMapping annotation. The value attribute in the annotation specifies the
URI that this handler should be mapped to.
● Spring provides a DI container that creates the beans and manages their life cycle.
This can be accessed via the ApplicationContext. The bean configuration can be
defined via XML, annotations or Java configuration (even Gradle).
● We also typically enable component scan for automatic creation of bean objects
from a given base package via annotations.
Spring MVC Error Handling
● Simpler error handling would constitute returning the HTTP status code
● 200 (OK), 201 (CREATED), 202 (ACCEPTED, resource yet to be created)
● 400 (Bad request), 401 (Authorization failure), 403 (Forbidden), 404 (Not found)
● However status codes provide basic error handling. Apart from status code, a
standard error structure can be returned to client, for example
application/vnd.error+json or application/vnd.error+xml. Spring HateOAS has
support for VndErrors.
● Writing vnd errors for each error condition is a pain and better way is to write
exception handlers (annotated with @ControllerAdvice) and throw exceptions for
all places where errors are generated.
https://blog.apigee.com/detail/restful_api_design_what_about_errors
● A controller advice class assists the controller class in various aspects like exception
handling. By default it covers all controllers.
Spring MVC – File Upload
● Prior to servlet 3.0, apache commons file upload was the only option to upload files
● Define the multipart bean in the web application context xml file. In mobile server
we use this:
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<beans:property name="maxUploadSize" value="99999999999" />
</beans:bean>
● Use Spring's MultipartFile class in the controller to handle file upload. We use this
in mobile server (MultipartFile.transferTo() API).
● Servlet 3.0 spec defines in built mechanism for file upload. It uses
javax.servlet.http.Part class for this.
● To use this, define the file size limit in the web.xml. Define a bean implementing
● Services Layer
● Captures the business logic, works with domain objects and executes a
transaction.
● URI Template allows a particular portion of the URI to be a variable. This can be
passed as an argument to the request handler which can take some action. For
example, /iprint/printers/airprint, /iprint/printers/email, /iprint/printers/mobile, here
only last element in the path is changing. To handle this in single method, use
/iprint/printers/{printerType}.
● Use @PathVariable annotation to read the path variables in the handler method
arguments.
● Matrix variables is another way to read values from the URI. It allows reading
name/val pairs and even multi-valued variables from the URI.
Reading URI Variables
● Matrix variables is another way to read values from the URI. It allows reading
name/val pairs and even multi-valued variables from the URI.
● /iprint/printers;airprint=true;email=false
● /iprint/printers;id=7flr1,7flr2,7flr3
● The major benefit is ability to specify multi valued attributes and reading them in a
● Another way is to read query parameters from th URI / Request Parameters. Use
@RequestParam annotation.
● http://localhost:8080/WebStore/products/product?category=laptop&price=700
● public String getProducts(@RequestParam String category, @RequestParam
String price) { }
View
● The View interface has render(Model, HttpRequest, HttpResponse). This interface is
implemented by many view technologies like InternalResourceView, VelocityView,
TilesView, RedirectView, FreeMarkerView.
● Controllers work with this interface thus any view technology can implement this
interface and work with Spring MVC.
● Use a view resolver to find the actual view instead of hardcoding (tightly coupling)
● Redirect View
● Forward/Redirect requests from one controller method to another
● Forward keeps the original request parameters and sends to the target controller
method
● Redirect generates a new request to the target and existing request parameters
are lost.
● To get the response in JSON / XML (both for view or REST), add dependency on
jackson-mapper-asl (json) and Spring oxm (xml). Use @XmlTransient /
@JsonIgnore to mark a particular field that should not be added to the response.
Use @XmlRootElement to mark the class name as the root.
Exception Handling
● @ResponseStatus annotation can be used to mark an exception class with status
code and message. Whenever that exception is thrown, Spring automatically takes
care of sending the appropriate status code and message.
● This annotation can also be used for a method to mark the status code returned by
that method.
● Need to add the interceptor class as a bean to the application spring configuration
xml as an interceptor.
● Interceptors can also be used to do special handling for certain scenarios, for
example promotional offers.
Spring Security Overview
● Can be used to add authentication and authorization to all layers including
presentation layer. Can be used for Spring MVC, REST and any non web based
application as well.
● Has authentication providers for LDAP, AD, PAM, Oauth and many more.
● Provides protection against many attacks like XSS, authentication & authorization,
session fixation, encryption etc.
● Spring Security also supports client authentication using certificates.
● One can setup an OAUTH Provider (which issues tokens) and validates those
tokens (OAuth Consumer)
● There is a inbuilt support to write unit tests to validate Oauth functionality. Basically
obtain the access token using mocks and leverage for futher unit tests.
● Application State represents the page that is loaded on the client web browser.
● Each resource has a state maintained by the web server. This is known as
Resource State.
● A client can initiate a resource state change by sending a representation (HTML form
submission / POST). Similarly server can change the application state by sending
the new representations of the web page. This is known as Representational State
Transfer. In another words, server sends a representation describing the current
state of the resource while client sends a representation to indicate the desired state
of the resource.
REST Basics
● All the web pages are connected via the hypermedia like <a> and <form> tags. This
drives the flow of application state (what pages client can navigate). Hence the term
'Hypermedia As The Engine Of Application State' (HATEOAS) is coined.
● The API (REST / Web) needs to be self descriptive using the hypermedia controls
so that client can discover the related resources and use them without following any
documentation.
● Also the API should not customize HTTP behavior to avoid requiring clients to use
some custom library. Lastly changing the API should not break the client. This all is
possible if APIs use basic HTTP concepts and are self descriptive.
● Think from web site and browser perspective. One browser can access any web site.
Even if web site changes still browser can access it. This works because all web site
pages are self descriptive (connected via hypermedia and have descriptive text). We
need to design web API's in a similar way.
● However one important difference is that a web browser is used by human beings
who can make decision on which link to click on a website by reading the description
but same is not true for web APIs as these are used by software agents. Some
predefined semantics are needed to define the hypermedia. This is a major
challenge. Need to read chapter 8 of the book to get better understanding. Anyways
it would still make it easy for developers to use.
HTTP Basics
● HTTP request
● Sent by the client if HTTP verbs like GET / POST / DELETE etc along with the
resource URL
● HTTP Response
● Status code indicating request processing status (200 – OK)
● Content type indicates the resource representation type (aka mime type e.g.
text/html, application/json)
● Entity body (resource representation)
● HTTP Methods
There are 8 methods in the RFC 2616. Below 4 are commonly used:
● GET – gets the representation of the resource (represented by URL). Default
method in browsers. Does not change the state of the resource / no side effects.
● POST – used to create resources. The response status code should be 201
(created) and a location header providing the url of the newly created resource.
● DELETE – destroy the resource
● HEAD – get the HTTP headers for the resource but not the representation (body).
● GET
● Gets the representation of the resource
● Safe method, does not modify the resource. However some logging / auditing is
ok.
● Common response is 200 (OK) or 301 (moved permanently)
● DELETE
● Removes a resource from the server
● Multiple delete requests for the same resource have no additional effect other than
● 204 (No content) deleted and there is no more message from server
● 404 (not found) / 410 (gone) – resource to be deleted does not exist
HTTP Basics
● POST.
● Creates a new resource
● Response
● 201 (created), accompanied with Location header indicating the newly created
resource url
● 202 (accepted), request to create resource accepted but not completed/started
yet.
● PUT
● Modifies an existing resource
● PUT can be used to create a new resource if the sender knows the url of to be
changes. This can be very inefficient for large representations and minor changes.
● PATCH allows sending delta changes (diff). There is a standard for XML and
● Not part of the HTTP spec and is an extension defined for the web API. Tools may
other resource
● Used to manage hypermedia links between resources.
● However depending on what kind of HTTP client/servers are there in the ecosystem,
one may want to use OPTIONS or HEAD request.
● PATCH request should only be used when you have full control of clients / server as
its a new option and not supported by many HTTP implementations
● WebDAV protocol defines additional HTTP methods for file handling like MOVE,
COPY, LOCK which can be used in file based applications.
JSON Basics
● JavaScript Object Notation
● Mime type “application/json”
● Based on JavaScript notations and used to represent data structures in language
neutral text format
● Conventions
● A list of values (array) is enclosed in square brackets e.g. [1,2,3]
● A collection (object) is a key value pair e.g. order {“id” : 1, items : [“a”, “b”, “c”]}
“collection” : {
“href” : “http://xyz.com/api/self“,
“items” : [
{ “href”: “http://xyz.com/api/next“ },
{ “href”: “http://xyz.com/api/prev“ }
]
}
● It also defines a template object (in the response) which client can use to send
● <img> - embeds an image into the current page. No user operation needed.
needed.
● <form method=GET> - request a new representation to server. User intervention
needed.
Hypermedia - URI
● URI Template
● URI type string that contains variables enclosed in { } which can be expanded to
● Every URL is a URI as well. A URL always has a representation while a URI may not
have. URI example thats not an URL, “urn:isbn:944849223”
● URI identifies a resource and is a superset.
● URL additionally identifies the mechanism to locate the resource like protocol http,
Workflow Control
● hypermedia describes the relationship between resources. <a> tag is an example for
this. Clicking it takes the browser to different page. Its an outbound link
● <img> is an embedded link and does not take the browser to different page.
● Note: JSON does not have hypermedia / url type. URLs are also represented as
string. Client needs to be informed via documentation about this.
Link
● HTTP also defines a "Link" header which is similar to <a> html tag. It can be used to
establish links for entity bodies that do not support hypermedia like binary image
files. e.g.
HTTP/1.1 200 OK
Content-Type: text/plain
Link: <http://www.example.com/story/part2>;rel="next"
● The HTTP LINK and UNLINK extensions also use the same header.
● Link tag is used to link two resources. Browsers typically support it only for linking
external style sheets. There is no end tag for this. It does not show up in the UI.
● Link relation attribute (rel) is what gives meaning to the relationship between two
resources (current and some other resource). The meaning depends on the domain.
This is where domain specific semantics come into picture.
● There is a link relations registry maintained by IANA, use those when appropriate.
While defining new relation names ensure they do not conflict with IANA names.
REST API Design Steps
● Identify what information client needs to access? Think about the structure of this
information. Typically its a hierarchical structure. For example, Printer->Name
(printer contains name). This is known as semantic descriptors for the application.
● Group the descriptors in their logical separate representations and Identify the
relationship between the different representations. Create a state diagram and put
names for each state transition.
REST API Design Steps
● Try using the IANA approved link relation names for your state transitions if possible.
● Decide on the media type. JSON does not have hypermedia so you might want to
use some other richer media type which can represent hypermedia like JSON-LD
(W3C standard) and HAL.
● Write a profile for your application semantics and embed those links in the response.
This will help client in understanding the meaning of various semantic descriptors
and their relations.
● Write Code
● Publish your home / start URL. This should be the only URL that you need to publish
and client should be able to discover the remaining API on its own.
REST API Design Guidelines
● Think in terms of the information to be returned to the client but not the URLs
● Use standard names for semantic relations / link rels and attributes.
● Do not map the database schema to the resources / api. It would become difficult to
extend the schema later on as clients will break.
not recommended. Sometimes media type is not under our control completely e.g.
if the client is using HTML5 form to talk to REST API.
● If you use hypermedia properly then versioning is not that critical. Hypermedia lets
you design APIs that can change easily. Two things to keep in mind:
● Server should not dump all hypermedia in single file and let clients use it, like
WSDL for web services. This will still lead to tight coupling and break clients when
APIs change. Instead put hypermedia controls that are relevant to current
resource state in a given resource.
● Clients need to discover the possible state transitions based on hypermedia and
use them.
REST Client
● Java API for JSON Processing (JSR 353)
● Use Java's URL class to open a connection to the REST service.
● Above is the Object Model API (DOM style), brings entire response in memory.
Other option is to use Streaming API (SAX style) which lets you parse the
response line by line.
● Spring RestTemplate
● This is even simpler way to write REST client but pulls in lot of Spring framework
dependencies.
● Uses HttpClient and Jackson Json mapper underneath
URL.
● Just inovke RestTemplate.getForObject() method and pass the URL along with
● GET
– Retrieve information
– Should not have side effects
– Repeatable (same data can be asked
multiple times)
– Can be conditional/partial (if-modified-since /
range)
– GET /users/22
HTTP Verbs
● DELETE
– Removes a resource
– Delete /users/21
HTTP Verbs
● POST
– Mostly used for creating resources (though
sometimes used for updating as well)
– The request body contains the details of the
resource to be created
– POST /users/21
{ “firstname” : “neeraj” }
– Once the resource is created, server sends a
HTTP 201 along with the URI of the newly
created resource in the Location header
HTTP Verbs
● PUT
– Used for updating resources
– PUT /users/21
{ “firstname” : “neeraj” }
HTTP Status
HTTP Status
HTTP Status
HTTP Content Negotiation
If Client specifies it accepts JSON while server only mentions XML in the
Content-Type then the negotiation would fail with 406.
We can create custom mime types as well to specify new versions of the
APIs and maintain compatibility with older versions.
Service/Application
SQL, NoSQL
Data Backends (MongoDB), Apache
Hadoop, REST etc
https://www.youtube.com/watch?
v=P05GlyrIz0o
Spring Data
● WebApplicationInitializer is equivalent to
web.xml.
● Helps in registering controllers, filters
programmatically for the web app
● Spring Boot even simplifies the
configuration further.