UNIT-V
Spring Framework
Spring is a lightweight framework. It can be thought of as a framework of
frameworks because it provides support to various frameworks such as Struts, Hibernate,
Tapestry, EJB, JSF, etc. The framework, in broader sense, can be defined as a structure
where we find solution of the various technical problems.
The Spring framework comprises several modules such as IOC, AOP, DAO, Context, ORM,
WEB MVC etc. We will learn these modules in next page. Let's understand the IOC and
Dependency Injection first.
Inversion Of Control (IOC) and Dependency
Injection
These are the design patterns that are used to remove dependency from the
programming code. They make the code easier to test and maintain. Let's understand this
with the following code:
1. class Employee{
2. Address address;
3. Employee(){
4. address=new Address();
5. }
6. }
In such case, there is dependency between the Employee and Address (tight coupling). In
the Inversion of Control scenario, we do this something like this:
1. class Employee{
2. Address address;
3. Employee(Address address){
4. [Link]=address;
5. }
6. }
Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the
code if our logic is moved to new environment.
In Spring framework, IOC container is responsible to inject the dependency. We provide
metadata to the IOC container either by XML file or annotation.
Advantage of Dependency Injection
o makes the code loosely coupled so easy to maintain
o makes the code easy to test
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.
Let's take the example of JdbcTemplate, you don't need to write the code for exception
handling, creating connection, creating statement, committing transaction, closing
connection etc. You need to write the code of executing query only. Thus, it save a lot of
JDBC code.
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 AOP Tutorial
Aspect Oriented Programming (AOP) compliments OOPs in the sense that it also
provides modularity. But the key unit of modularity is aspect than class.
AOP breaks the program logic into distinct parts (called concerns). It is used to increase
modularity by cross-cutting concerns.
A cross-cutting concern is a concern that can affect the whole application and should be
centralized in one location in code as possible, such as transaction management,
authentication, logging, security etc.
Why use AOP?
It provides the pluggable way to dynamically add the additional concern before, after or
around the actual logic.
Understanding Scenario I have to maintain log and send notification after calling
methods that starts from m.
Problem without AOP We can call methods (that maintains log and sends notification)
from the methods starting with m. In such scenario, we need to write the code in all the
5 methods.
But, if client says in future, I don't have to send notification, you need to change all the
methods. It leads to the maintenance problem.
Solution with AOP We don't have to call methods from the method. Now we can define
the additional concern like maintaining log, sending notification etc. in the method of a
class. Its entry is given in the xml file.
In future, if client says to remove the notifier functionality, we need to change only in the
xml file. So, maintenance is easy in AOP.
Where use AOP?
AOP is mostly used in following cases:
o to provide declarative enterprise services such as declarative transaction management.
o It allows users to implement custom aspects.
AOP Concepts and Terminology
AOP concepts and terminologies are as follows:
o Join point
o Advice
o Pointcut
o Introduction
o Target Object
o Aspect
o Interceptor
o AOP Proxy
o Weaving
Spring Web Model-View-Controller
o Model - A model contains the data of the application. A data can be a single object
or a collection of objects.
o Controller - A controller contains the business logic of an application. Here, the
@Controller annotation is used to mark the class as the controller.
o View - A view represents the provided information in a particular format. Generally,
JSP+JSTL is used to create a view page. Although spring also supports other view
technologies such as Apache Velocity, Thymeleaf and FreeMarker.
o Front Controller - In Spring Web MVC, the DispatcherServlet class works as the
front controller. It is responsible to manage the flow of the Spring MVC application.
Understanding the flow of Spring Web MVC
o As displayed in the figure, all the incoming request is intercepted by the
DispatcherServlet that works as the front controller.
o The DispatcherServlet gets an entry of handler mapping from the XML file and
forwards the request to the controller.
o The controller returns an object of ModelAndView.
o The DispatcherServlet checks the entry of view resolver in the XML file and invokes
the specified view component.
Advantages of Spring MVC Framework
Let's see some of the advantages of Spring MVC Framework:-
o Separate roles - The Spring MVC separates each role, where the model object,
controller, command object, view resolver, DispatcherServlet, validator, etc. can be
fulfilled by a specialized object.
o Light-weight - It uses light-weight servlet container to develop and deploy your
application.
o Powerful Configuration - It provides a robust configuration for both framework
and application classes that includes easy referencing across contexts, such as from
web controllers to business objects and validators.
o Rapid development - The Spring MVC facilitates fast and parallel development.
o Reusable business code - Instead of creating new objects, it allows us to use the
existing business objects.
o Easy to test - In Spring, generally we create JavaBeans classes that enable you to
inject test data using the setter methods.
o Flexible Mapping - It provides the specific annotations that easily redirect the
page.
Spring Containers
Spring Framework provides two of the most fundamental and Important
packages, they are
the [Link] and [Link] packages
. Code in these packages provides the basis for Spring’s Inversion of
Control/Dependency Injection features. Spring containers are responsible for
creating bean objects and injecting them into the classes. The two containers
are namely,
1. BeanFactory(I) – Available in [Link]
package.
2. ApplicationContext(I) – Available in [Link]
package.
The BeanFactory Interface
This is the root interface for accessing a Spring bean container. It is the actual
container that instantiates, configures, and manages a number of beans. These
beans collaborate with one another and thus have dependencies between
themselves. These dependencies are reflected in the configuration data used
by the BeanFactory. This interface is implemented by the objects that hold a
number of bean definitions, each uniquely identified by a String name. The most
common implementation class used for this BeanFactory
is XmlBeanFactory available in [Link]
package.
Note: BeanFactory is deprecated from Spring 3.0.
The ApplicationContext Interface
This interface is designed on top of the BeanFactory interface. The
ApplicationContext interface is the advanced container that enhances
BeanFactory functionality in a more framework-oriented style. While the
BeanFactory provides basic functionality for managing and manipulating beans,
often in a programmatic way, the ApplicationContext provides extra functionality
like MessageSource, Access to resources, Event propagation to beans,
Loading of multiple (hierarchical) contexts etc. There are so many
implementation classes that can be used such
as ClassPathXmlApplicationContext, FileSystemXmlApplicationContext,
AnnotationConfigWebApplicationContext etc.
Difference Table
BeanFactory ApplicationContext
It is an advanced container that extends
the BeanFactory that provides all basic
It is a fundamental container that provides functionality and adds some advanced
the basic functionality for managing beans. features.
It is suitable to build Web applications,
integration with AOP modules, ORM
It is suitable to build standalone applications. and distributed applications.
It supports all types of bean scopes such
It supports only Singleton and Prototype as Singleton, Prototype, Request,
bean scopes. Session etc.
It does not support Annotations. In Bean
Autowiring, we need to configure the It supports Annotation based
properties in XML file only. configuration in Bean Autowiring.
BeanFactory ApplicationContext
ApplicationContext interface extends
MessageSource interface, thus it
This interface does not provides messaging provides messaging (i18n or
(i18n or internationalization) functionality. internationalization) functionality.
Event handling in the
ApplicationContext is provided through
BeanFactory does not support Event the ApplicationEvent class and
publication functionality. ApplicationListener interface.
In BeanFactory, we need to manually register The ApplicationContext automatically
BeanPostProcessors and registers BeanFactoryPostProcessor and
BeanFactoryPostProcessors. BeanPostProcessor at startup.
ApplicationContext loads all the beans
BeanFactory will create a bean object when and creates objects at the time of
the getBean() method is called thus making it startup only thus making it Eager
Lazy initialization. initialization.
BeanFactory interface provides basic features
only thus requires less memory. For ApplicationContext provides all the
standalone applications where the basic basic features and advanced features,
features are enough and when memory including several that are geared
consumption is critical, we can use towards enterprise applications thus
BeanFactory. requires more memory.
Dependency Injection by Constructor
We can inject the dependency by constructor. The <constructor-arg> subelement
of <bean> is used for constructor injection. Here we are going to inject
1. primitive and String-based values
2. Dependent object (contained object)
3. Collection values etc.
Dependency Injection by setter method
We can inject the dependency by setter method also. The <property> subelement
of <bean> is used for setter injection. Here we are going to inject
1. primitive and String-based values
2. Dependent object (contained object)
3. Collection values etc.
Injecting primitive and string-based values by constructor and
setter method
Let's see the simple example to inject primitive and string-based values by setter method.
We have created three files here:
o [Link]
o [Link]
o [Link]
Spring - Listening to Standard events
Spring core framework provides application level event firing and event listening
which is based on the standard Observer design pattern.
There are built-in application events available or we can create our own custom
events in spring.
This tutorial focuses on built-in application events provided by Spring container.
Spring build-in events
Build-in Event Description
ContextRefreshedEvent Event fired when an ApplicationContext gets initialized or refreshed
(refreshed via [Link]() call).
ContextStartedEvent Event fired when [Link]() method is called.
ContextStoppedEvent Event fired when [Link]() method is called
ContextClosedEvent. Event fired when [Link]() method is called.
RequestHandledEvent This event can only be used in spring MVC environment. It is called just after
an HTTP request is completed.
A Publisher
Now let’s create a publisher of that event. The publisher constructs the
event object and publishes it to anyone who's listening.
To publish the event, the publisher can simply inject
the ApplicationEventPublisher and use the publishEvent() API
Alternatively, the publisher class can implement
the ApplicationEventPublisherAware interface, and this will also inject the
event publisher on the application startup. Usually, it's simpler to just inject
the publisher with @Autowire.
As of Spring Framework 4.2, the ApplicationEventPublisher interface
provides a new overload for the publishEvent(Object event) method that
accepts any object as the event. Therefore, Spring events no longer need
to extend the ApplicationEvent class.
A Listener
Finally, let's create the listener.
The only requirement for the listener is to be a bean and
implement ApplicationListener interface
Notice how our custom listener is parametrized with the generic type of
custom event, which makes the onApplicationEvent() method type-safe.
This also avoids having to check if the object is an instance of a specific
event class and casting it.
And, as already discussed (by default Spring events are synchronous),
the doStuffAndPublishAnEvent() method blocks until all listeners finish
processing the event.