UNIT4
UNIT4
Spring Framework
Spring is a lightweight framework developed by Rod Johnson in 2003. 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.
Spring Modules
The Spring framework comprises of many modules such as core, beans, context,
expression language, AOP, Aspects, Instrumentation, JDBC, ORM, OXM, JMS,
Transaction, Web, Servlet, Struts etc. These modules are grouped into Test,
Core Container, AOP, Aspects, Instrumentation, Data Access / Integration, Web
(MVC / Remoting) as displayed in the following diagram.
Test
This layer provides support of testing with JUnit and TestNG.
2. Context
3. Expression Language(Spel)
IoC Container
The IoC container is responsible to instantiate, configure and assemble the
objects. The IoC container gets informations from the XML file and works
accordingly. The main tasks performed by IoC container are:
1. BeanFactory
2. ApplicationContext
Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface. To
use the BeanFactory, we need to create the instance of XmlBeanFactory class as
given below:
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationContext.xml");
Dependency Lookup
The Dependency Lookup is an approach where we get the resource after
demand. There can be various ways to get the resource for example:
A obj = A.getA(); This way, we get the resource (instance of A class) by calling
the static factory method getA().
1. 20.5M
Dependency Injection
The Dependency Injection is a design pattern that removes the dependency of
the programs. In such case we provide the information from the external source
such as XML file. It makes our code loosely coupled and easier for testing. In such
case we write the code as:
class Employee
{
Address address;
Employee(Address address)
{
this.address=address;
}
public void setAddress(Address address)
{
this.address=address;
}
In such case, instance of Address class is provided by external source such as XML
file either by constructor or setter method.
Two ways to perform Dependency Injection in
Spring framework
Spring framework provides two ways to inject dependency
2. By Constructor
3. By Setter method
1. Employee.java
2. applicationContext.xml
3. Test.java
Employee.java
void show(){
System.out.println(id+" "+name);
}
}
applicationContext.xml
We are providing the information into the bean by this file. The constructor-arg
element invokes the constructor. In such case, parameterized constructor of int
type will be invoked. The value attribute of constructor-arg element will assign
the specified value. The type attribute specifies that int parameter constructor will
be invoked.
</beans>
Test.java
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
Singleton Pattern
Factory Pattern
Strategy Pattern
Spring AOP
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.
It provides the pluggable way to dynamically add the additional concern before,
after or around the actual logic. Suppose there are 10 methods in a class as given
below:
class A{
public void m1(){...}
public void m2(){...}
public void m3(){...}
public void m4(){...}
public void m5(){...}
public void n1(){...}
public void n2(){...}
public void p1(){...}
public void p2(){...}
public void p3(){...}
}
There are 5 methods that starts from m, 2 methods that starts from n and 3
methods that starts from p.
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.
Join point is any point in your program such as method execution, exception
handling, field access etc. Spring supports only method execution join point.
Advice
Pointcut
Introduction
It means introduction of additional method and fields for a type. It allows you to
introduce new interface to any advised object.
Target Object
It is the object i.e. being advised by one or more aspects. It is also known as
proxied object in spring because Spring AOP is implemented using runtime
proxies.
Aspect
Interceptor
AOP Proxy
Weaving
It is the process of linking aspect with other application types or objects to create
an advised object. Weaving can be done at compile time, load time or runtime.
Spring AOP performs weaving at runtime.
AOP Implementations
AOP implementations are provided by:
1. AspectJ
2. Spring AOP
3. JBoss AOP
Inversion of Control
Spring – Beans
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 . Bean definition
contains the information called configuration metadata, which is needed for
the container to know the following −
How to create a bean
Bean's lifecycle details
Bean's dependencies
The Spring Framework supports the following five scopes, three of which are
available only if you use a web-aware ApplicationContext.
1 singleton
This scopes the bean definition to a single instance per Spring IoC container (default).
2 prototype
This scopes a single bean definition to have any number of object instances.
3 request
This scopes a bean definition to an HTTP request. Only valid in the context of a web-
aware Spring ApplicationContext.
4 session
This scopes a bean definition to an HTTP session. Only valid in the context of a web-
aware Spring ApplicationContext.
5 global-session
This scopes a bean definition to a global HTTP session. Only valid in the context
Autowiring in Spring
Autowiring feature of spring framework enables you to inject the object
dependency implicitly. It internally uses setter or constructor injection.
Autowiring can't be used to inject primitive and string values. It works with
reference only.
Advantage of Autowiring
It requires the less code because we don't need to write the code to inject the
dependency explicitly.
Disadvantage of Autowiring
No control of programmer.
Autowiring Modes
Following are the autowiring modes, which can be used to instruct the Spring
container to use autowiring for dependency injection. You use the autowire
attribute of the <bean/> element to specify autowire mode for a bean definition.
1 no
This is default setting which means no autowiring and you should use explicit bean
reference for wiring. You have nothing to do special for this wiring. This is what you
already have seen in Dependency Injection chapter.
2 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. It then
tries to match and wire its properties with the beans defined by the same names in
the configuration file.
3 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. It
then tries to match and wire a property if its type matches with exactly one of the
beans name in configuration file. If more than one such beans exists, a fatal
exception is thrown.
4 constructor
Similar to byType, but type applies to constructor arguments. If there is not exactly
one bean of the constructor argument type in the container, a fatal error is raised.
5 autodetect
Spring first tries to wire using autowire by constructor, if it does not work, Spring
tries to autowire by byType.
Spring Annotation
Spring Framework started using annotations from the release 2.5. Due to
the way they are defined, annotations provide a lot of context in their
declaration.
@Autowired
@Configuration
@ComponentScan
Though, there is lists of the activities that take place behind the scenes between the
time of bean Instantiation and its destruction, but this chapter will discuss only two
important bean life cycle callback methods which are required at the time of bean
initialization and its destruction.
Beans can be notified after creation and all properties are set, and before they are
destroyed and removed from the bean container. This involves specifying the callback
method to be invoked by the container. This is done in XML by specifying attributes init-
method=”myinit”, for the initialization callback, and destroy-method=”mydestroy”, for the
destroy callback. “myinit” and “cleanUp” are names of instance methods in the bean
class.
Initialization callbacks
Implementingthe org.springframework.beans.factory.InitializingBean interfa
ce allows a bean to perform initialization work after all necessary properties
on the bean are set by the container. The InitializingBean interface
specifies exactly one method:
Destruction callbacks
Implementingthe org.springframework.beans.factory.DisposableBean interf
ace allows a bean to get a callback when the container containing it is
destroyed. The DisposableBean interface specifies one method: