Spring Tutorial (1)
Short Description
spring...
Description
g
2012
Spring
Course Material
SUDHEER NARESH i technologies 6/30/2012
SPRING
SUDHEER
Introduction:
This course explains various utilities provided by Spring Framework. Spring is a lightweight open-source application framework that simplifies the enterprise application
development in Java. In J2EE application development, we got some component technologies and service
technologies. By using the component and service technologies of J2EE, we can develop a good
enterprise level Business applications. Component Technologies are 1. Servlet 2. JSP 3. EJB Service Technologies are 1. JNDI (Java Naming and Directory Interface) 2. JMS (Java Messaging Service) 3. Java Mail 4. Java Transaction Service (JTS) 5. JAAS (Java Authentication And Authorizations Service) We use Servlet and JSP technologies of J2EE for the development of Web applications. We use EJB technology for the development of Distributed and Enterprise applications. While developing enterprise applications through EJB, we got the following problems. 1. EJB Component development requires multiple Java files and xml files. So it makes burden on the developer or programmer. 2. EJB’s cannot run without a container/Server. So to test an EJB a server is mandatory. 3. While testing an EJB, if it files wants to be modified then we need to shutdown the server and after modification again we need to restart the server and test. If you
want to test then we need to follow the same procedure. EJB’s are heavy weight components and having a lot of dependency with a server.
Architecture Diagrams: 1. Before Spring:-
Presentation View Layer (JSP)
Business Layer
Controller
Session
Entity
(Servlet)
Bean
Bean
DB NARESH i technologies
SPRING
SUDHEER
Struts
EJB
2. After Spring:-
Presentation View Layer (JSP)
Business Layer
Controller
BL
(Servlet)
(Spring)
DAL (Hibernate)
Struts
Spring Framework:
Spring is a multi-tier open-source lightweight application framework, addressing most
infrastructure concerns of enterprise application. It is mainly a technology dedicated to enable us to build applications using POJOs. Spring is a complete and a modular framework. It means Spring Framework can be used for all layers implementation for a Real-time applications (or) Spring can be used for the
development of a particular layer of real time application. Spring Framework is said to be a non-invasive or non-intrusive framework. It means Spring Framework does not force a Programmer to extend or implement their classes
from any pre-defined class or interface given by Spring API. In case of Struts Framework, it will force the programmer that the programmer class must extend from the base class provided by Struts API. So Struts is called as an invasive/intrusive Framework.
NARESH i technologies
DB
SPRING
SUDHEER
Spring Framework simplified J2EE application development by introducing POJO model
and is important because of following three reasons. 1. Simplicity 2. Testability 3. Loose-Coupling Spring provides simplicity, because of POJI or POJO model and is easy to test, because
Spring can be executed within a server and even without server. Spring provides loose-coupling, because of Inversion of Control mechanism. Spring Framework can be used to develop any kind of Java Application. It means we can
develop starting from console application up to enterprise level application. Unlike other Frameworks, Spring Framework has its own container, So Spring runs even without Server also.
Benefits of Spring Framework
Spring Framework addresses most of the infrastructure functionalities of the enterprise applications. This comes with number of benefits such as 1. Spring Framework address important areas that many other frameworks do not like. It includes support for managing business objects and exposing their services to the presentation tier components that the web and desktop applications can access the same business objects. 2. Spring is complete and modular. This is because Spring Framework has a layered architecture, meaning that you can choose to use just about any part of it in isolation, yet its architecture is internally consistent. 3. Spring Framework provides perfect support for write code that is easy to test. Meaning, Spring Framework is the best framework for test-driven projects. 4. Spring is an increasingly important integration technology; its role is recognized by several large vendors. 5. Spring can eliminate the creation of singletons and factory classes seen on many projects. 6. Spring can facilitates good programming practice by reducing the cost of programming interfaces, rather than classes, almost to zero
Spring Modules
NARESH i technologies
SPRING
SUDHEER
In Spring 1.x, the framework has divided into seven well-defined modules. But in Spring 2.x the framework is divided into 6 modules only. 1. Spring Core Module 2. Spring J2EE Module 3. Spring JDBC Module 4. Spring ORM Module 5. Spring AOP Module. 6. Spring MVC Module.
Spring ORM
Spring AOP
Spring
Spring
Spring
J2EE
MVC
JDBC Spring Core
Spring Core Module:
(Inversion of Controller)
This module provides the basic functionality required for a Spring application Spring core module generates a high-level object of the Spring framework called
“BeanFactory” or “ApplicationContext”. Spring core module applies IOC (Inversion of Control) or Dependency Injection for
generating Spring IOC container called as BeanFactory. All frameworks will follows as an high level object is created first and it will have take
care about the low level object required for the application. For Example Struts Framework ActionServlet Hibernate Framework SessionFactory Spring Framework BeanFactory
Spring Context (J2EE) Module:
Spring J2EE module is an extension to core module where core module creates container and J2EE module make it as a framework.
NARESH i technologies
SPRING
SUDHEER
Spring J2EE module adds real-time services like Emailing,JMS,Timer,JNDI,Remoting and internationalization
Spring DAO module
This module is providing an abstraction layer on top of existing JDBC technology and it
avoids the repeated JDBC code from an application. Another advantage of this module is, we no need to handle exception while working with database. Because in Spring all exceptions are unchecked exceptions.
Spring ORM module
This module is also work with database. Spring ORM module provides an abstraction layer on top of existing ORM tools. When compared with Spring DAO, Spring ORM has two benefits. a. Data transfer will be done in the form of Objects. b. An ORM tool always throws unchecked exceptions. Spring provides an abstraction layer on top existing ORM layer which avoids boils plate
code. By without using this ORM modules, Spring can directly communicating with ORM tools
like hibernate, iBATIS etc. Spring AOP
In real-time applications, business logic needs additional services. If we combinable implement business logic along with services, then we will get the following problems. a. The size of the application increases, so that complexity increases. b. If any modification is required in a service then in each business method we need to
do modifications separately. We can avoid the above problems by using Aspect Oriented Programming in Spring. In AOP we can separated the business logic and secondary services.
Spring MVC Module
In this module we can develop the following two operations. a. We integrate our Spring framework with other frameworks like Struts and JSF etc. b. We can develop complete MVC applications, by without using any other framework.
NARESH i technologies
SPRING
SUDHEER
Spring Core Module (or) Spring IOC Tight coupling and loose coupling between objects:
While developing Java Applications one object will collaborate or communicate with
another object for providing services to the clients. If one object is communicating with another object i.e. If one object is calling the business method of another object then we can say that there is a coupling between the
two objects. In Object to Object collaboration, one object becomes dependent object and the other
object becomes caller object. For example, If Traveler and Car are the two classes and Traveler class is depending on car. In this case Traveler Object is called dependent Object and that car Object is called Caller object. Coupling refers to dependencies that exist between two things. Consider two classes for
an example. If one class is highly dependent on the implementation details of another class this is considered as tight coupling. Sometimes even both classes might be dependent on each other’s implementation details making it more coupled. If a class is tightly coupled with another class, changing implementation details of main (depending) class will affect all other dependent classes.
In the above example, Traveler Object is depending on Car Object. So Traveler class
creating an object of Car class inside it. If directly the object is created in the dependent class then there exists tight coupling
and the above example there is a tight coupling between Traveler and Car Object. In order to overcome tight coupling between objects, Spring Framework uses Dependency Injection Mechanism.
NARESH i technologies
SPRING
SUDHEER
With the help of POJO or POJI model and through Dependency Injection then it is
possible to achieve loose coupling. In the above example, Traveler and Car are tightly coupled. If you want to achieve loose coupling between the objects Traveler and Car, we need to rewrite the application like the following. Example:
Vehicle.java package com.nit.Spring.ioc; public interface Vehicle { public void move(); } Car.java package com.nit.Spring.ioc; /** * @author sudheer * */ public class Car implements Vehicle{ @Override public void move() { // Business Logic } }
Bike.java package com.nit.Spring.ioc; /** * @author sudheer * */ public class Bike implements Vehicle { @Override
NARESH i technologies
SPRING
SUDHEER
public void move() { // Business Logic } } Traveler.java package com.nit.Spring.ioc; /** * @author sudheer * */ public class Traveler { Vehicle vehicle; public void setVehicle(Vehicle vehicle) { this.vehicle = vehicle; } public void startJourney() { vehicle.move(); } }
In the above example, through Dependency Injection mechanism, Spring container will inject either Car object or Bike Object into Traveler by calling setter method. So if Car object is replaced with Bike object then no changes are required in Traveler class. It means there is a loose coupling between Traveler Object and Vehicle Object.
Inversion of Control (IoC):
NARESH i technologies
SPRING
SUDHEER
Inversion of Control is an architectural pattern describing an external entity (that is container) used to wire objects at creation time by injecting there dependencies, that is,
connecting the objects so that they can work together in a system. In other words the IoC describes that a dependency injection needs to be done by an
external entity of creating the dependencies by the component itself. Dependency Injection is a process of injecting the dependencies in to an Object.
Types of IoC:
Inversion of Control means, separating the implementation of an object from how the
object is constructed. In case of Spring Framework the framework will take care of about the object creation and injecting the dependent object required. As a programmer we are responsible for
only implementation of the business logic. There are two types of IoC’s a. Dependency Lookup b. Dependency Injection
Dependency Lookup
In this type of IoC, when one object is collaborating with another object, the first object
has to get all the dependencies required explicitly by itself. In Dependency Lookup, an external person does not provide collaborating objects
automatically to first object. In dependency lookup of IoC, the first object is responsible for obtaining its collaborating
objects from the container or registery etc. For Example: a. In Servlet with Connection pooling, Servlet object depends on datasource object. In this case nobody automatically gives DataSource object to Servlet object. Servlet itself goes to JNDI registry and takes DataSource object from the registery by performing lookup operation.
NARESH i technologies
SPRING
SUDHEER
Servlet
Pool 3
DS
DATA SOURCE
Co nn
4
Con n Co nn
Con n
1 2 Key/DS JNDI Register
b. In Servlet to EJB communication, Servlet depends on EJB Object, For calling the business logic implemented in an EJB. In this communication nobody will provide EJB object to Servlet object automatically. Servlet itself goes to EJB container and gets the required EJB object from it. It means there is a Dependency Lookup. Dependency Injection:
In this type of IoC, when one object is collaborating with another object, some other external person will provide the collaborating object to the dependent object
automatically. In this type of IoC the first object is not responsible to explicitly take the collaborating
objects required. It means the first object does not perform any lookup operation. In case of Spring Framework, the external person who performs dependency injection is called Spring IoC container. NARESH i technologies
SPRING
SUDHEER
EJB 3.0 Technology and Spring Framework both are supporting Dependency Injection type of IoC.
Why Dependency Injection
In developing huge systems using the object oriented programming methodology, we generally divide the system into objects where each of the objects representing some
functionality. In this case, the objects in the system use some other objects to complete the given request. The objects with which our object collaborates to provide the services are
known as its dependencies. The traditional ways of obtaining the dependencies are by creating the dependencies or by pulling the dependencies using some object factory classes and methods or from the naming registery. But these approaches result in some problems which are described
below: i. The complexity of the application increases. ii. The development time-dependency increases. iii. The difficulty for unit testing increases. To solve the above stated problems we have to use a push model, that is, inject the dependent objects into our object instead of creating or pulling the dependent objects. The process of injecting (pushing) the dependencies into an object is known as Dependency Injection (DI) .This gives some benefits as described below. i. The application development will become faster. ii. Dependency will be reduced.
Spring Core Container and Beans
Spring core container is the basis for the complete Spring Framework. It provides an
implementation for IoC supporting dependency injection. This provides a convenient environment to program the basic to enterprise application
avoiding the need of writing the factory classes and methods in most of the situations. This even helps one to avoid the need of programming in singletons. The Spring core container takes the configurations to understand the bean objects that it
has to instantiate and manage the lifecycle. The one important feature of the Spring core container is that it does not force the user to have any one format of configurations, as most of the framework which are designed NARESH i technologies
SPRING
SUDHEER
to have XML based or Property file base configuration, or programmatically using the Spring beans API. But in most of the cases we use XML based configurations since they
are simple and easy to modify. The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the
aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring. Its responsibilities include instantiating or sourcing application objects, configuring such
objects, and assembling the dependencies between these objects. 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. This implementation allows you to express the objects that compose your application, and the doubtless rich interdependencies between such objects, in terms of XML. The XmlBeanFactory takes this XML configuration metadata and uses it to create a fully configured system or application.
Your Buss Objects
Configuration Metadata
Spring Container
Produces Fully Configure System (Ready For Use)
Configuration Metadata
As can be seen in the above image, the Spring IoC container consumes some form of configuration metadata; this configuration metadata is nothing more than how you (as
NARESH i technologies
SPRING
SUDHEER
an application developer) inform the Spring container as to how to “instantiate,
configure, and assemble [the objects in your application. This configuration metadata is typically supplied in a simple and intuitive XML format. When using XML-based configuration metadata, you write bean definitions for those beans that you want the Spring IoC container to manage, and then let the container do
it's stuff. Spring configuration consists of at least one bean definition that the container must manage, but typically there will be more than one bean definition. When using XMLbased configuration metadata, these beans are configured as elements inside a
top-level element. Find below an example of the basic structure of XML-based configuration metadata.
Instantiating a container:
The Spring core container can be instantiated by creating an object of any one of the
BeanFactory or ApplicationContext classes supplying the Spring beans configurations. The various implementation of BeanFactory are mainly differentiated based on the Spring beans configuration format they understand and the way they locate the
configurations. The following code snippet shows the sample code that instantiates the Spring container using the Spring Beans XML configuration file as configuration metadata. Syntax: BeanFactory beans = new XmlBeanFactory (new FileSystemResource (“beans.xml”)); In the preceding code snippet we are using XmlBeanFactory implementation for instantiating the Spring container with “beans.xml” file as a configuration file, as the
NARESH i technologies
SPRING
SUDHEER
name describes the ClassPathXmlApplicationContext locates the XML configuration file
in the classpath We can even use ApplicationContext to instantiate the container; the following code
snippet shows the sample code to instantiate Spring. Syntax ApplicationContext context = new ClassPathXmlApplicationContext (“beans.xml”);
In code snippet we are using ClassPathXmlApplicationContext implementation to instantiate the Spring container with “beans.xml” file as a configuration file, as the name describes the ClassPathXmlApplicationContext locates the XML configuration file in the classpath.
Types of Dependency Injection:
Dependency Injection classified as the following three types. i. Setter Injection ii. Constructor Injection iii. Interface Injection In Spring Framework we use Setter and Constructor Injection but not Interface Injection. In Struts 2.X, we have Interface Injection.
Setter Injection
In this type of Dependency Injection, the Spring (IoC) container uses setter method in the
dependent class for injecting its dependencies (Collaborators). Spring Container knows whether to perform Setter Injection or Constructor Injection by
reading information from an external file called as Spring Configuration file. In case of Setter Injection, the class must contain a setter method to get the dependencies; otherwise Spring container does not inject the dependencies to the
dependent object. Example
NARESH i technologies
SPRING
SUDHEER
In the above example, Class A is called Dependent and Class B is called Collaborator. In the Dependent class there is a setter method for getting collaborator object. So we call
it as Setter Injection. In Spring Framework, we call each class as a “Spring Bean” .This Spring Bean is no where
related with Java Bean. Spring Bean and Java Bean both are not same because a Java bean needs definitely a public default constructor. But in a Spring bean sometimes we include default constructor
and sometimes we do not. In Spring bean classes; there exists the following three types of dependency values. i. Dependency in the form of Primitive Values ii. Dependency in the form of Objects iii. Dependency in the form of Collections
NARESH i technologies
SPRING
SUDHEER
Dependency in the form of Primitives
The Spring container understands whether dependency is in the form of primitive or not, whether setter injection or constructor injection is required information by reading
Spring configuration file. Spring Configuration file is identified with .xml If the dependency in the form of primitives then we can directly provide value in the xml
file for that property. In Spring configuration file, we used element. So Spring container
understands that there is a Setter Injection in the bean class. Inside element, we have used element. So Spring container
understands that the dependency is in the form of Primitives. Syntax: 100 In Spring Configuration file, we can use as a sub element of tag or
value as an attribute of tag Syntax: Example a. Project Structure
NARESH i technologies
SPRING
SUDHEER
b. PrimitivesDemo.java
C. PrimitivesClient.java
NARESH i technologies
SPRING
SUDHEER
c. Primitives.xml (Configuration File)
d. Output
Description of PrimitivesClient Step 1: A. Spring environment starts by loading Spring Configuration file into Resource Object.
NARESH i technologies
SPRING
SUDHEER
B. We call this Stpe1 as a bootstrapping of Spring Framework C. Resource is an interface and classpath. Resource is an implementation class given by Spring Framework. D. Both Resource interface
and
classpath
Resource
class
are
given
in
org.springframewok.core.io package Syntax: Resource resource = new ClassPathResource (“beans.xml”); Step 2:
A. Spring IoC container object will be created by reading bean definitions from the Resource object. B. Spring IoC container is called BeanFactory and this container is responsible for creating the bean objects and for assigning its dependencies. C. BeanFactory is an interface and XmlBeanFactory is an implementation class of it. D. BeanFactory is an interface given in org.springframework.beans.factory and XmlBeanFactory is a class given in org.springframework.beans.factory.xml package Syntax: BeanFactory beanFactory = new XmlBeanFactory(res); Step 3:
A. B. C. D.
Get the bean object from the Spring container by calling getBean() method. While calling getBean() method, we need to pass the bean id as a parameter. getBean() always return object. We need to type cast the object into our Spring Bean type.
Syntax: Object obj = beanFactory.getBean(“pd”); PrimitivesDemo pd = (PrimitivesDemo)obj; E ) Call the business method of the SpringBean by using the object. Pd.getDetails () Dependencies in the form of Objects
NARESH i technologies
SPRING
SUDHEER
While constructing Spring Beans (Pojo Classes), one Spring bean class depends on
another Spring Bean class, for performing some business operations. If one bean class is depending on another bean class object then we call it as an object
dependency. If one bean class is depending on another bean class object then the Spring IoC
container is responsible for creating and injecting the dependencies. In Spring Configuration file we have two ways to inform the container about this object dependency. 1. By using inner beans. 2. By using element.
By using inner beans
Inner bean means a bean which is added for a property by without an id in the xml file. In case of inner bean definition with setter injection, we should add the element, inside the tag in xml.
NARESH i technologies
SPRING
SUDHEER
In the client application, if we call factory.getBean(“od1”) then internally the Spring Framework will do the following operations.
ObjectDemo1 od1 = new ObjectDemo1 (); ObjectDemo2 od2 = new ObjectDemo2(); od1.setOd(od2); In the above example, ObjectDemo1 object is depending on ObjectDemo2 object. So the Spring container first created the ObjectDemo2 object and after that the container created ObjectDemo1 object.
Drawbacks of InnerBeans
An Inner bean does not have any id. So it is not possible to get that bean object
individually from the IoC container. If another bean class is also depending on the same bean then in the xml file , again we
need to add the inner bean definition. In order to overcome the above two problems of inner beans, we need to use element in the Spring configuration file.
NARESH i technologies
SPRING
SUDHEER
element
When dependencies are in the form of objects then to inform the IoC container, in
Spring configuration xml file, we need to configure element. element is associated with either local or parent and bean attributes. When we add element then we need to pass id of collaborator bean to its attribute, because the dependency is in the form of objects.
Local
If local attribute is used with the element then the Spring IoC container will verify
for the collaborator bean within same container. In general, we try to configure all Spring beans into a single Spring configuration file. But it is not mandatory, because we can create multiple Spring configuration files also.
NARESH i technologies
SPRING
SUDHEER
In the above xml file, both the dependent bean and its collaborator bean are configured in the same xml file. It means into the same Spring IoC container. So we can use local
attribute with element. By loading this above xml file, we will get the Spring IoC container object called BeanFactory.
Syntax Resource resource = new ClassPathResource(“spconfig.xml”); BeanFactory beanFactory = new XmlBeanFactory (resource, null);
In Spring IoC, it is possible to create parent and child factories.
Syntax Resource resource = new ClassPathResource(“parent.xml”); BeanFactory beanFactory = new XmlBeanFactory (resource, null); Resource resource1 = new ClassPathResource (“child.xml”); BeanFactory beanFactory1= new XmlBeanFactory (resource1, beanFactory);
In the above syntax, beanFactory1 is a child container of beanFactory.
NARESH i technologies
SPRING
SUDHEER
DependentBean is available in beanFactory (Parent Container). It means both dependent bean and its collaborator bean are not available in same container. So we cannot use local attribute with element.
Parent
If parent attribute is used with element then the Spring IoC container will search for the collaborator bean always at parent container. But not in the Same container.
parent.xml
child.xml
In the above xml files, dependent bean is available in beanFactory1 (child container) and collaborator bean is available in beanFactory (parent container). So parent attribute is suitable with element.
Bean NARESH i technologies
SPRING
SUDHEER
In this attribute is used with element then the Spring IoC container first verifies for the collaborator bean in the same factory. If not available then it will search in the
parent factory. Bean is the combination of both local and parent. Bean first works like local and otherwise it works like parent.
parent.xml
Child.xml
Note: 1. While using element, if the given id is not found then null will be assigned into the object, but an exception is not thrown. 2. If id is not found but class is not a suitable for the required type then an exception will be thrown by the IoC container. The exception name is org.springframework.beans.UnsatisfiedDependencyInjectionException.
NARESH i technologies
SPRING
SUDHEER
Example: 1. Project Structure
ObjectDemo1.java
ObjectDemo2.java
NARESH i technologies
SPRING
SUDHEER
ObjectClient.java
NARESH i technologies
SPRING
SUDHEER
Parent.xml
Child.xml
NARESH i technologies
SPRING
SUDHEER
Output:
Dependencies in the form of Collections
While creating a Spring bean (Pojo) , the bean class can use any one of the following four
types of collections as a dependency. 1. Set 2. List 3. Map 4. Properties Except the above four types of collections, if the Spring bean class uses any other type of collection as a dependency then the Spring container does not inject that collection object to the Spring bean. In this case spring programmer is responsible for injecting the collection object manually.
Set Collection
If a Spring bean has a property of collection type set then in the Spring configuration file
we need to use element to inform the Sprig IoC. In Spring configuration file we can use and tags as a sub elements of
tab. While configuring element in the xml file it does not allow duplicate values.
Because set collection is unique collection. In Spring Framework if one bean class is collaborating with another bean class then Spring IoC container first creates collaborator bean object and after that dependent bean object
Merging
The merging of collection is allowed in the Spring 2.0. A parent-style element can have child-style element which inherit and
overrides the values from the parent collection. For collection merging you need to specify merge=true attribute on the element of child bean definition.
NARESH i technologies
SPRING
SUDHEER
Project Structure
DemoSet.java
SetClient.java
NARESH i technologies
SPRING
SUDHEER
Set.xml
NARESH i technologies
SPRING
SUDHEER
Output
In Client application when we can call factory.getBean(“child) then internally Spring Framework executes the following code. Set set = new HashSet(); set.add(“Sudheer”); set.add(“YS Jagan”); set.add(“Rama”);
List Collection
If a Spring bean is depending on a collection of type List then in Spring configuration file,
we need to configure element. We can use and tags as sub elements of List The differences between Set and List Collections are Set Set is an unordered collection Set does not allow dublicate values Set does not allow index based accessing Set does not support list iterator
List List is an ordered collection List allows dublicate values List allows index base accessing List support list iterator
Merging
The merging of collection is allowed in the Spring 2.0. A parent-style element can have child-style element which inherit and
overrides the values from the parent collection. For collection merging you need to specify merge=true attribute on the element of child bean definition. NARESH i technologies
SPRING
SUDHEER
Example 1. Project Structure
2. DemoList.java
NARESH i technologies
SPRING
SUDHEER
3. DemoListClient.java
4. List.xml
NARESH i technologies
SPRING
SUDHEER
Output:
What is the difference between an inner class and a nested class? A non-static inner class is called inner class and a static inner class is called nested class. public class A class A { { static class B class B { { } } } } What is Map.Entry in java? Map.Entry is a class . Here map is an interface and Entry is a static class of Map Interface. A Map stores data in the form of key/value pairs and we call each pair as one NARESH i technologies
SPRING
SUDHEER
entry. In the statement Map.Entry the meaning is we can create static classes inside an interface. We call those classes as nested classes. public interface Map { static class Entry { } } If a Map Collection contains 3 key/value pairs then internally it means 3 objects of Map.Entry class. Map Collection
In a Spring bean if we take collection type as Map then in the Spring configuration file
we should configure the element. In Spring configuration file we need to use the sub element of map as . In a map collection one entry represents key/value pair. We use sub element of entry as either or element.
Merging
The merging of collection is allowed in the Spring 2.0. A parent-style element can have child-style element which inherit and
overrides the values from the parent collection. For collection merging you need to specify merge=true attribute on the element of child bean definition.
Example 1. Project Structure
NARESH i technologies
SPRING
SUDHEER
2. DemoMap.java
3. DemoClient.java
NARESH i technologies
SPRING
SUDHEER
4. Map.xml
NARESH i technologies
SPRING
SUDHEER
OUT PUT
Properties Collection
Properties collection also stores data in the form key/value pairs. But both key/value are
considered as Strings. If we take Properties collection in the Spring bean then in the Spring configuration file,
we need to use element. The sub element of is and the element does not any have subelements.
Merging
The merging of collection is allowed in the Spring 2.0. NARESH i technologies
SPRING
SUDHEER
A parent-style element can have child-style element which inherit
and overrides the values from the parent collection. For collection merging you need to specify merge=true attribute on the element of child bean definition.
Example: 1. Project Structure
2. DemoProps.java
NARESH i technologies
SPRING
SUDHEER
PropsClient.java
3. Props.xml
NARESH i technologies
SPRING
SUDHEER
Output:
Constructor Injection
The constructor Injection method of dependency injection is the method of injecting the dependencies of an object through its constructor arguments. In this mechanism the dependencies are pushed into the object through the constructor argument at the time
of instantiating. Constructor Injection is a Dependency Injection variant where an object gets all its dependencies via the constructor. This is PicoContainer's most important feature. The most important benefits of Constructor Injection are: It makes a strong dependency contract It makes testing easy, since dependencies can be passed in as Mock Objects It's very succinct in terms of lines of code Classes that rely on Constructor Injection are generally Good Citizens A dependency may be made immutable by making the dependency reference
final In the case when the object is instantiated by using some factory method then passing the dependencies as arguments to the factory method is also considered as constructor
injection since the dependencies are injected at the time of constructing the object. The following code snippet shows the sample class that allows the injection of its dependencies as constructor arguments.
The element
The bean definition can describe to use a constructor with zero or more arguments to
instantiate the bean The element describes one argument of the constructor, which means that to specify a constructor with multiple arguments we need to use
element multiple times. The zero tags in bean definition describes the use of the no-argument constructor. The arguments specified in the bean definition correspond to either a specific index of the constructor argument list or are supposed to be matched generically by type. element supports four attributes NARESH i technologies
SPRING
SUDHEER
Index
This attribute takes the exact index in the constructor argument list. This is used to avoid ambiguities like in case of two arguments being of the same type
Type
This argument takes the type of this constructor argument
Value
A short-cut alternatives to a child elment ‘value’
Ref
As short-cut alternative to a child element ref bean
Example Project Structure
ConstructorDemo.java
NARESH i technologies
SPRING
SUDHEER
ConstructorClient.java
Constructor.xml
NARESH i technologies
SPRING
SUDHEER
OUT PUT
In the client application when we call beanF.getBean(“con”) then internally Spring Framework executes the following statements. ConstructorDemo cd = new ConstructorDemo (“Sachin”, 34);
Circular Dependency Injection
If A and B are two classes/beans and if A depends on B and B depends on A then we will
get Circular Dependency. When circular dependency is occurred then we cannot solve this problem with the help
of Constructor Injection. In this case, instead of constructor injection we need to use setter injection. For Example
NARESH i technologies
SPRING
SUDHEER
In a client application, when we call factory.getBean(“a”) then Spring IoC container is trying to create class A object but ‘A’ need ‘B’ object so the container tries to create B class object. But ‘B’ also need ‘A’ Object , So A & B objects are not
created and Spring Framework throws BeanCurrentlyInCreationException In order to solve the circular dependency problem between class A and Class B we need to change or replace constructor injection with setter injection at class A.
Example
NARESH i technologies
SPRING
SUDHEER
1. A.java
2. B.java
3. CircularDemo.java
NARESH i technologies
SPRING
SUDHEER
Cic.xml
In the client application, when we call factory.getBean(“a”) internally the following steps are executed i. Spring container creates a mock object of class A using default constructor of ii.
class A. Spring container create a class ‘B’ object by passing the mock object of class ‘A’
iii.
into its constructor. Spring container injects class B object into class A by calling setter method.
NARESH i technologies
SPRING
SUDHEER
iv.
Finally, class A object is given back to the client application.
Setter Injection
Constructor Injection
Setter Injection makes bean object as
Constructor injection makes bean object as
mutable
immutable
In Setter Injection partial injection of
In constructor injection partial injection of
dependencies is possible
dependencies is not possible
Setter Injection can solve circular
Constructor Injection does not solve
dependency problem
circular dependency problem
Setter Injection overrides the constructor
Constructor Injection does not override
Injected value
setter injected value
Bean Autowiring Wiring a bean means configuring a bean along with its dependencies into an xml file. By default autowiring is disabled. It means the programmer has to explicitly wire the
bean properties into an xml file. If autowiring is enabled then Spring Framework will take care about injecting the
dependencies and programmer is no need to configure into an xml file explicitly. Bean autowiring is only supported if the dependencies are in the form of objects. To enable autowiring we should add autowire attribute to the element. The different autowire values are i. byName ii. byType iii. autodirect iv. none (default) byName In this case Spring Framework attempts to find out a bean in the configuration file whose
id is matching with property name to be wired. If a bean found with the id as property name then that class object will be injected into
that property by calling setter injection. If no id is found then that property remains unwired.
NARESH i technologies
SPRING
SUDHEER
byType In this case the Spring Framework attempts to find out a class in the xml file whose
name is matching with the property type to be wired or not. If found then injects that class object by using setter Injection. If no class found in xml with the same name then that property remains unwired. If a class is found in xml for more than once then Spring Framework throws UnSatisfiedDependencyException.
NARESH i technologies
SPRING
SUDHEER
Constructor This autowire type is equal to byType. But here constructor injection will be executed. Example: Previous Example modify with constructor Autodirect This type of autowiring first work likes a constructor and if not then it works like byType. Validating the Dependencies In Spring Framework either in explicit wiring or in auto wiring if all properties are not
configured in xml but still Spring container create an object of the bean class. By default Spring container does not verify whether all properties are set in xml or not.
NARESH i technologies
SPRING
SUDHEER
If we enable the dependency validation then Spring container verifies whether all dependencies are set or not. If not the container does not create an object and throws
an Exception. To enable dependency validation we need to add dependency-check attribute for the
. The different values of dependency-check attribute are i. no (by default) ii. Simple iii. Object iv. All Simple In this case Spring container verifies for primitives and collections are set or not. If not
set then exception will be thrown. Objects In this case the Spring Container verifies whether objects are set or not. If not the container throws an Exception All In this case the container verifies for objects, primitives and collections. Example
DemoBean.java
NARESH i technologies
SPRING
SUDHEER
TestBean.java
ValidateClient.java
NARESH i technologies
SPRING
SUDHEER
Validate.xml
Output
Bean Initialization and Destruction While creating our bean class in Spring apart from injections, we can also create
methods for performing initialization and cleanup code required for the bean class. In a Spring bean, if we want to add some initialization and cleanup code then we need to
implement our Spring bean class from InitializingBean and DisposableBean interfaces. If we implement the above two interfaces then in our Spring bean class we have to override the following two methods. i. afterPropertiesSet()
NARESH i technologies
SPRING
SUDHEER
ii. destroy() Code Snippet
In the above bean class when a client request is given for getting the bean object then
internally the following steps are executed. a. Object is created b. Properties are injected. c. afterPropertiesSet() called d. Now object is given to Client application. Before container is removing the object then container first calls the destroy() and then
removes that object from the memory. In the above code snippet the drawback is our class is not a POJO class. Because it is
implementing from predefined interfaces given by the framework. So we can rewrite the above bean class by adding our own methods for initialization and cleanup;
In this case the bean into xml we have to add init-method and destroy-method attributes for element. In this case container will do the following before giving the object to client. a. Object is created b. Properties are injected c. Inint() called d. Now object is given to client. When Container is going to to remove the object first it calls tearsDown() method and after that Object is removed.
Example
NARESH i technologies
SPRING
SUDHEER
Project Structure:
LifeBean.java
ClientForLife.java
NARESH i technologies
SPRING
SUDHEER
Init.xml
Bean Scopes in Spring Framework You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to 'bake in' the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext).
NARESH i technologies
SPRING
SUDHEER
Scope singleton
Definition Scopes a single bean definition to a single object instance per Spring
prototype request
IoC container. Scopes a single bean definition to any number of object instances. Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a
session
web-aware Spring ApplicationContext. Scopes a single bean definition to the lifecycle of a HTTP Session.
global session
Only valid in the context of a web-aware Spring ApplicationContext. Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.
The Singleton Scope When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
NARESH i technologies
SPRING
SUDHEER
The Prototype Scope The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made (that is, it is injected into another bean or it is requested via a programmatic getBean() method call on the container). As a rule of thumb, you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.
Bean Instantiation Spring Framework instantiates or gets a Spring bean object by using the following three ways. i. By Calling Constructor. ii. By Calling Static Factory method iii. By Calling an instance factory method. By Calling Constructor When we call getBean(“id1”) method from the client application then the Spring IoC container uses ‘new’ operator and calls constructor of the class and gets an object of the
bean class. After getting the bean object, it will apply injections and after that other initializations and then returns that bean object to the client application.
NARESH i technologies
SPRING
SUDHEER
If we change the bean scope to prototype then the IoC container gets|created new
object for each call to the getBean(“id1”) method. By Calling static factory method By default Spring IoC container makes each bean as singleton. But when the scope of a
bean is changed to prototype then the bean object becomes non-singleton. If a Spring programmer doesn’t want to make a Spring bean as prototype bean then the programmer has to explicitly make the bean class as singleton. To make a bean class as Singleton the following rules are need to be followed. a. Create a Private static object to the class, inside the class. b. Create a private constructor c. Create a public static factory method.
Code Snippet
While configuring the above bean class into Spring configuration file, we need to inform the Spring IoC container that calls static factory method of the bean class to get an
object of the bean class. To inform the Spring IoC container we should add an attribute called factory-method to the element.
NARESH i technologies
SPRING
SUDHEER
When getBean(“sb”) method is called from the client application then the IoC container will get the bean object by using the following statement internally. SampleBean sb = new SampleBean(); How to create Synchrozed Singleton class in java? If we add Synchronized keyword for the static factory method then the class becomes
synchronized singleton class. By Calling Instance factory method In this approach Spring IoC container class the factory method defined in one class to get
an object of another bean class. In Java we have two types of factory methods 1. Static factory method 2. Instance factory method A factory method may or may not return same class object. But a factory method must return an object.
NARESH i technologies
SPRING
SUDHEER
In the below xml, for the bean “tb1” we have removed class attribute and we have
added factory-bean attribute. In a Client application when we call factory.getBean . (“id1”) internally the following statements are executed by the container. TestBean1 tb1 = new TestBean1(); TestBean1 tb = tb1.getInstance ();
ean Life Cycle
1. 2. 3. 4. 5.
Does not Exist Instantiation Initialization Service Destroy
Doesn’t Exist
Factory.getBean(“id”)
Instantiation 1. Inject Dependenc 2. Calls aftPropSet 3. Call customInit
Destroy
Service
Initialization
NARESH i technologies
SPRING
SUDHEER
Spring JDBC Introduction:
JDBC technology is required either directly or indirectly for getting a connection with the
database. Without using JDBC technologies we cannot able connect with databases using Java. If a programmer is directly working with JDBC technology then there are some problems facing by the Java Programmer. a. JDBC technology exceptions are checked exceptions. There we must put try and catch blocks in the code at various places and it increases the complexity of the applications. b. In a Java Program, repetitive code is required to perform operations on databases from the various client applications. The repetitive code is like loading the drivers, connection opening, creating a statement and finally closing the objects of JDBC. This kind of repetitive code, we call as Boilerplate Code. c. In JDBC, if we open the connection with database then we are responsible to close it. If the connection is not closed then later at some point of time, we may get out of connections problem. d. JDBC throws error codes of the database when an exception is occurred sometimes the error codes are unknown of the Java Programmer and error codes are different from one database to another database. Therefore developing JDBC applications
using those error codes will make our application as database dependent. Spring JDBC frame work has provided an abstraction layer on top of the existing JDBC
technology. Spring JDBC layer concentrates on avoiding connection management coding and error management and Spring JDBC programmer will concentrate on construction and
execution of the SQL operations. Spring framework has provided an exception translator and it translates the checked exceptions obtained while using JDBC into unchecked exceptions of Spring type and
finally the unchecked exceptions are thrown to the Java Programmer. While working with Spring JDBC, the programmer no need to open and close the database connection and it will taken care by the Spring framework.
NARESH i technologies
SPRING
SUDHEER
Table 1.1 The following table describes which actions is developer’s responsibility and which actions are taking care by Spring itself:
Sno
Action
Developer
Spring
1
Define parameters for connection
Y
2
connection opening
3
Specify the statement for SQL
Y
4
Declaration of parameters & providing
Y
5
value for parameter. Prepare Statement & execute
Y
6
Loop setup for result iteration(if required)
Y
7
Defining work for each iteration
8
exception handling
Y
9
Handling transactions
Y
10
Connection, statement & resultset closing
Y
Y
Y
The package hierarchy
The Spring Framework's JDBC abstraction framework consists of four different packages,
namely core, datasource, object, and support. The org.springframework.jdbc.core package contains the JdbcTemplate class and its
various callback interfaces, plus a variety of related classes. A sub-package named org.springframework.jdbc.core.simple contains the
SimpleJdbcTemplate class and the related SimpleJdbcInsert and SimpleJdbcCall classes. Another sub-package named org.springframework.jdbc.core.namedparam contains the
NamedParameterJdbcTemplate class and the related support classes. The org.springframework.jdbc.datasource package contains a utility class for easy DataSource access, and various simple DataSource implementations that can be used for NARESH i technologies
SPRING
SUDHEER
testing and running unmodified JDBC code outside of a J2EE container. The utility class provides static methods to obtain connections from JNDI and to close connections if necessary. It has support for thread-bound connections, e.g. for use with
DataSourceTransactionManager. Next, the org.springframework.jdbc.object package contains classes that represent RDBMS queries, updates, and stored procedures as thread safe, reusable objects. This approach is modeled by JDO, although of course objects returned by queries are “disconnected” from the database. This higher level of JDBC abstraction depends on the
lower-level abstraction in the org.springframework.jdbc.core package. Finally the org.springframework.jdbc.support package is where you find the SQLException translation functionality and some utility classes. Exceptions thrown during JDBC processing are translated to exceptions defined in the org.springframework.dao package. This means that code using the Spring JDBC abstraction layer does not need to implement JDBC or RDBMS-specific error handling. All translated exceptions are unchecked giving you the option of catching the exceptions that you can recover from while allowing other exceptions to be propagated to the caller.
DataSource:
A Java application can get a connection with a database using the following two ways. i. java.sql.DriverManager (class) ii. javax.sql.DataSource (Interface) Spring framework always uses DataSource interface to obtain a connection with the database internally. DataSource interface is also having different types of implementation. i. Basic Implementation, it is equal to DriverManager. ii. Connection pooling implementation. iii. Transaction implementation.
NARESH i technologies
SPRING
SUDHEER
While using DataSource, it is always does not mean that we are working with connection pool. If internal implementation class is connection pool enabled then only the
DataSource will provide a logical connection from the pool. In Spring framework we use any one of the following two implementation classes of
DataSource interface i. org.springframework.jdbc.datasource.DriverManagerDataSource ii. org.springframework.jdbc.datasource.BasicDataSource The above two classes are suitable, when our Spring application is under development
mode. In Production mode, the Spring application uses connection pooling service provided by
the application servers. In the above two classes, DriverManagerDataSource is given by Spring framework and it is equal to DriverMangerClass.It means Spring framework internally opens a new
connection. BasicDataSource is given by apache .common-dbcp project and it is better than DriverManagerDataSource. Because BasicDataSource has inbuilt connection pooling implementation.
Configuration
In Spring Configuration file, we need to configure the following four properties to obtain the connection with the database. i. driverClassName ii. url iii. username iv. password
.00 . Syntax: 1. The following code snippet for DriverManagerDataSource configuration.
NARESH i technologies
SPRING
SUDHEER
Code Snippet: 1.1 The above snippet for configure DriverManagerDataSource
NARESH i technologies
SPRING
SUDHEER
2. The following code snippet for BasicDataSource configuration in Spring configuration file.
Code Snippet: 1.2 The above snippet for configure BasicDataSource
Installation:
The following jar file is set as class path for working with Spring Jdbc framework. A. org.springframework.jdbc-3.0.6.RELEASE.jar
Central Classes in Spring JDBC framework JdbcTemplate:
It simplifies the use of JDBC since it handles the creation and release of resources. This helps to avoid common errors such as forgetting to always close the connection.
NARESH i technologies
SPRING
SUDHEER
It executes the core JDBC workflow like statement creation and execution, leaving Data access using JDBC Spring Framework application code to provide SQL and extract results. This class executes SQL queries, update statements or stored procedure calls, imitating
iteration over ResultSets and extraction of returned parameter values. It also catches JDBC exceptions and translates them to the generic, more informative,
exception hierarchy defined in the org.springframework.dao package. Code using the JdbcTemplate only need to implement callback interfaces, giving them a clearly defined contract. The PreparedStatementCreator callback interface creates a prepared statement given a Connection provided by this class, providing SQL and any necessary parameters. The same is true for the CallableStatementCreator interface which creates callable statement. The RowCallbackHandler interface extracts values
from each row of a ResultSet. The JdbcTemplate can be used within a DAO implementation via direct instantiation with a DataSource reference, or be configured in a Spring IOC container and given to DAOs as a bean reference.
Instantiation:
JdbcTemplate class depends on DataSource object, because JdbcTemplate opens a connection internally with a Database through DataSource Object only. JdbcTemplate class can be created in the following two ways. 1. JdbcTemplate jtemplate= new JdbcTemplate(); 2. JdbcTemplate jtemplate = new JdbcTemplate(DataSource ds)
. In case first case, DataSource object is injected to JdbcTemplate by calling setter injection
Ex: jt.setDataSource (DataSource obj) Spring IOC Container will inject DataSource object into JdbcTemplate. But we need to configure them into Spring configuration file.
Configuration:
NARESH i technologies
SPRING
SUDHEER
The following code snippet demonstrate how to configure JdbcTemplate in Spring configuration file by using either using code snippet 1.1
Approach 1:
Using Setter Injection
Code snippet: 1.3 The above code snippet for JdbcTemplate for instantiation by using setter Injection
Approach 2:
Using Constructor Injection
NARESH i technologies
SPRING
SUDHEER
Code snippet: 1.4 The above code snippet for JdbcTemplate for instantiation by using constructor Injection API Methods: void execute (String sql)
This is method is used to execute both DDL and DML operations on the Database. This method allows only static sql command. It means the sql command should not
contain ‘?’ symbol This is suitable to perform DDL operations on the Database. Because, for DML operations, this method doesn’t return the count value back to the programmer.
int update(String sql)
This method is used to execute only DML operations on the database. It means either insert or update or delete.
NARESH i technologies
SPRING
SUDHEER
If we use a single parameter then we need to pass static SQL command and otherwise
we can use the following method. Syntax: int update(Strinq sql,object obj[]) In case of dynamic command, first we need to store all objects into an object array and then we need to pass that object array as a parameter. Syntax: object params[] = {“Spring”,”jdbc”}; int k = jt.update(“insert into spring values(?,?), params);
int queryForInt(String sql) And int queryForInt(String sql, Object params [])
This method is used for executing a select operation on database, which returns an integer. We can pass either static or dynamic sql command to this method Syntax: Static: int k = jt.queryForInt (“select count (*) from emp”);
long queryForLong(String sql) And long queryForLong (String sql, Object obj[])
If our query command (select) is going to return a long value then we use this command. We can pass both static and dynamic sql commands to this method. Syntax: long l = jt.queryForLong (“select sum (sal) from emp”); long l = jt.queryForLong (“select sum(sal) from emp where deptno = ?”, new Object []{new Integer (20)});
object queryForObject (String sql, Class clazz)
This method is used to get the result of select command in the form of required object. We have to pass the required class type, in the form a class Object as a second parameter Syntax: Object obj = jt.queryForObject(“select sysdate from dual” ,Date.class); Object obj = jt.queryForObject(“select avg(sal) from emp”,Integer.class);
NARESH i technologies
SPRING
SUDHEER
List queryForList(String sql) And List queryForList (String sql, Object obj [])
This method is used for selecting one or more rows/records from the database table. Internally JdbcTemplate stores all the rows into a array for each row and finally stores all these object array into a collection of type ArrayList and the list object is given back to
the programmer. While iterating the collection the programmer has type cast the result in to an object array. Syntax: List l = jt.queryForList (“select * from EMP”); Iterator it = l.iterator(); while (it.hasNext ()) { Map map = (Map) it.next (); }
Example 1. Project Structure
NARESH i technologies
SPRING
SUDHEER
2. EmployeeDao.java
NARESH i technologies
SPRING
SUDHEER
EmployeeDaoImpl.java
NARESH i technologies
SPRING
SUDHEER
NARESH i technologies
SPRING
SUDHEER
Jdbc.xml
TemplateClient.java
NARESH i technologies
SPRING
SUDHEER
Outputs
Invoke reaming API methods as similar to empDao.createEmp(query) Loading DataSourse Properties from ResourceBundle
While configuring a DataSource implementation class into a Spring configuration xml file,
we are placing directly the connection properties into the xml file. Instead of directly placing the values into the xml file, we can load the values at runtime
for the DataSource properties from ResourceBundle. If we want to get the DataSource properties at run time from a ResourceBundle then while configuring the bean into xml file. We should put the bundle keys with expression language into the xml file.
NARESH i technologies
SPRING
SUDHEER
Syntax:
In to the above bean definition, the values are passed at runtime from the ResourceBundle. The Bundle is like the following.
In Spring Framework, we have a predefined class given called PropertyPlaceholderConfigure and this class will load/read the data from bundle and it
will write the values into the bean definition of xml PropertyPlaceholderConfigure is a class given in org.springframework.beans.factory.config package.
Example
NARESH i technologies
SPRING
SUDHEER
1. Project Structure
Jdbc.properties
Jdbc.xml
NARESH i technologies
SPRING
SUDHEER
DataSourceDemo.java
Output:
NARESH i technologies
SPRING
SUDHEER
NamedParameterJdbcTemplate
The NamedParameterJdbcTemplate class adds support for programming JDBC statements using named parameters (as opposed to programming JDBC statements
using only classic placeholder ('?') arguments. NamedParameterJdbcTemplate class wraps a JdbcTemplate, and delegates to the
wrapped JdbcTemplate to do much of its work. This section will describe only those areas of the NamedParameterJdbcTemplate class that Data access using JDBC differ from the JdbcTemplate itself; namely, programming JDBC statements using named parameters.
If you like, you can also pass along named parameters (and their corresponding values)
to a NamedParameterJdbcTemplate instance using the (perhaps more familiar) Map-based style. (The rest of the methods exposed by the NamedParameterJdbcOperations - and
NARESH i technologies
SPRING
SUDHEER
implemented by the NamedParameterJdbcTemplate class) follow a similar pattern and will not be covered here.)
Another nice feature related to the NamedParameterJdbcTemplate (and existing in the same Java package) is the SqlParameterSource interface. You have already seen an example of an implementation of this interface in one of the preceding code snippets
(the MapSqlParameterSource class). The entire point of the SqlParameterSource is to serve as a source of named parameter values to a NamedParameterJdbcTemplate. The MapSqlParameterSource class is a very simple implementation that is simply an adapter around a java.util.Map, where the keys
are the parameter names and the values are the parameter values. Another SqlParameterSource implementation is the BeanPropertySqlParameterSource class. This class wraps an arbitrary JavaBean (that is, an instance of a class that adheres to the JavaBean conventions), and uses the properties of the wrapped JavaBean as the
source of named parameter values. Syntax:
NARESH i technologies
SPRING
SUDHEER
Remember that the NamedParameterJdbcTemplate class wraps a classic JdbcTemplate template; if you need access to the wrapped JdbcTemplate instance (to access some of the functionality only present in the JdbcTemplate class), then you can use the
NARESH i technologies
SPRING
SUDHEER
getJdbcOperations () method to access the wrapped JdbcTemplate via the JdbcOperations interface. Calling Procedures/Functions:
To call a procedure or a function from a database, we- have two approaches in Spring i.e.
by extending StoredProcedure class and by without extending it. If we want to call a procedure or a function then the simple approach is by extending our
bean class from StoredProcedure. (Abstract class but not abstract methods). If we want to call procedures/functions of the database then the following steps are need to be followed. 1. Extend the bean class from StoredProcedure. 2. Call the base class constructor from our bean class by passing datasource object, name of the procedure name or function as parameters. Syntax: super (datasource,”pro1”); 3. Declare the keys in the form of sqlParameter objects that are used as keys for map objects. 4. Call execute () method from the business method of the bean by passing the input values in the form of map object. 5. Read the output values returned into the map object from the procedure or function.
Example 1. Project Structure
DBSteps:
NARESH i technologies
SPRING
SUDHEER
StoredProcedureDemo.java
NARESH i technologies
SPRING
SUDHEER
NARESH i technologies
SPRING
SUDHEER
Proc.xml
ProcedureDemo.java
NARESH i technologies
SPRING
SUDHEER
Using Connection Pooling in Spring:
When we configure BasicDataSource into Spring configuration xml file then implicitly Spring application is using connection pool service. Because BasicDataSource class has a
inbuilt connection pool service. The inbuilt connection is only suitable for small scale applications, but not for production
level applications. If a Spring application or any other java application wants to get a connection from an external connection pool then the application need a mediator object called DataSource,
which is configured in the server. When a DataSource is configured by the server administrator then it will be stored in
JNDIRegistery with some JNDI name. If any Java application wants to get connection pool service of a server then the
application has to get the DataSource object from the Registry. If an application wants to get DataSource object then it need JNDI name.
D A
2
1
POOL
T A
Con n
S
Con n
6
DS
O
con nn n
U
7
R
NARESH i technologies
S
KEY 5
E
co nn n
DS
3
JNDIRegistery
SPRING
SUDHEER
4
In case of Spring Framework, the Programmer is not responsible for opening and closing
of the Database connection and it is done by JdbcTemplate. JdbcTemplate need JNDI name of the DataSource object to configure the
JndiObjectFactoryBean. JdbcTemplate is a class which depends on JndiObjectFactoryBean for getting a
connection from the connection pool. In the Spring configuration file we need to configure JndiObjectFactoryBean and JdbcTemplate like the following.
Configuring a connection pool in weblogic server Stp1 : Start the Weblogic server Start -> Programs->Bea Products – Weblogic 8.x Step2: Open the browsers and type the following url http://localhost:7001/console
NARESH i technologies
SPRING
SUDHEER
Step 3: At Left Side expand Services -> expand JDBC -> Select DataSources -> Cick on Configure a new JDBC Data Source
NARESH i technologies
SPRING
SUDHEER
Step 4 : Click on Configure a new JDBC Connection Pool...
NARESH i technologies
SPRING
SUDHEER
NARESH i technologies
SPRING
SUDHEER
Step 5: Click on continue button
Step 6: Click on Test Configuration button -> Finish Example: Project Structure:
NARESH i technologies
SPRING
SUDHEER
ConnectionPoolingDemo.java
NARESH i technologies
SPRING
SUDHEER
Pooling.xml
JndiClient.java
NARESH i technologies
SPRING
SUDHEER
Rowset Support in Spring JDBC
In a Spring bean class while selecting records from a table instead of calling
queryForList() method, we can also call queryForSet() method. The advantage of using queryForSet() method is , it returns the selected records in the form of a RowSet object and this RowSet object can be transferred across between from
one machine to another machine. Because RowSet object is Serialized object. In Spring Framework a class given to support RowSet behavior called SqlRowSet this
class is given in org.springframework.jdbc.support.rowset.* package If we store the selected records in a RowSet object then we can use methods of RowSet for moving the cursor in different directions for reading our data. Syntax
RowMapper Interface:
When selecting records from a database table internally Spring Framework stores all the records into a ResultSet object and the framework converts the rows into map objects
and those map objects are stored in List. Instead of Storing each row of a ResultSet in a map object, if we want to store in a POJO
class object then we need to use RowMapper interface. In case of RowMapper internally for each record of the ResultSet ,its mapRow() method is
NARESH i technologies
SPRING
SUDHEER
NARESH i technologies
SPRING
SUDHEER
NARESH i technologies
SPRING
SUDHEER
NARESH i technologies
SPRING
SUDHEER
SPRING ORM
The Spring Framework provides integration with Hibernate, JDO, Oracle TopLink, iBATIS SQL Maps and JPA: in terms of resource management, DAO implementation support, and transaction strategies. For example for Hibernate, there is first-class support with
lots of IoC convenience features, addressing many typical Hibernate integration issues. Some of the benefits of using the Spring Framework to create your ORM DAOs include: Ease of testing. Spring's IoC approach makes it easy to swap the implementations and config locations of Hibernate SessionFactory instances, JDBC DataSource instances, transaction managers, and mappes object implementations (if needed). This makes it
much easier to isolate and test each piece of persistence-related code in isolation. Common data access exceptions. Spring can wrap exceptions from your O/R mapping tool of choice, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This allows you to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches/throws, and exception declarations. You can still trap and handle exceptions anywhere you need to. Remember that JDBC exceptions (including DB specific dialects) are also converted to the same hierarchy, meaning that
you can perform some operations with JDBC within a consistent programming model. General resource management. Spring application contexts can handle the location and configuration of Hibernate SessionFactory instances, JDBC DataSource instances, iBATIS SQL Maps configuration objects, and other related resources. This makes these values easy to manage and change. Spring offers efficient, easy and safe handling of persistence resources. For example: related code using Hibernate generally needs to use the same Hibernate Session for efficiency and proper transaction handling. Spring makes it easy to
NARESH i technologies
SPRING
SUDHEER
transparently create and bind a Session to the current thread, either by using an explicit 'template' wrapper class at the Java code level or by exposing a current Session through the Hibernate SessionFactory (for DAOs based on plain Hibernate API). Thus Spring solves many of the issues that repeatedly arise from typical Hibernate usage, for any
transaction environment (local or JTA). Integrated transaction management. Spring allows you to wrap your O/R mapping code with either declarative, AOP style method interceptor, or an explicit 'template' wrapper
class at the Java code level. While integrating Spring Framework with ORM tools we have the following two
approaches. We can directly use the ORM tool API into Spring bean for performing DataAccessLayer
logic. We can use the abstraction layer given by Spring Framework on top of existing ORM
tools for performing DataAccessLayer Operations. ORM is a translator or an engine it acts as a bridge between a Java application and a
database server and internally translates object into text format and vice versa. Spring ORM module provides DAO pattern implementation. The advantage of Spring Framework has given a single exception hierarchy irrespective
of the persistence technology used. While integrating Spring Framework with hibernate we use the abstraction layer which is
given by Spring Framework and it internally uses hibernate ORM framework. Spring Framework has provided a central class to perform database operations in the
form of objects called HibernateTemplate. While integrating the Spring Framework with hibernate then the Hibernate setup required need to be configured with a Spring Framework provided class called
LocalSessionFactoryBean. While integrating Spring with hibernate we do not require to construct hibernate
configuration file. Instead we need to configure LocalSessionFactory. LocalSessionFactoryBean constructs SessionFactory of hibernate internally. HibernateTemplate is a class which internally uses Session API of hibernate. As a part of Spring – Hibernate integration we configure the following two classes given
by Spring Framework. i. LocalSessionFactoryBean ii. HibernateTemplate The above two classes are given in org.springframework.orm.hibernate3 package.
NARESH i technologies
SPRING
SUDHEER
While configuring LocalSessionFactoryBean class into spring configuration file then we
need to configure the following three properties. i. mappingResources ii. hibernateProperties iii. dataSource LocalSessionFactoryBean depends on dataSource object for opening the connection
with database. mappingResources is a collection of hibernate mapping files and it is a properties of
collection type List. hibernatProperties is a collection of type properties. LocalSessionFactoryBean class is containing setter injections for all the Properties. So at the time of configuring into Spring configuration file, we need to use element.
Code Snippet:
NARESH i technologies
SPRING
SUDHEER
HibernateTemplate is a class which provides convenient methods for the Spring developers to transfer to and from data between an application and database in the
form of objects. HibernateTemplate depends on LocalSessionFactoryBean. In HibernateTemplate we have a property called SessiongFactory and it is of type LocalSessionFactoryBean. So we need to configure the HibernateTemplate like the following
NARESH i technologies
SPRING
SUDHEER
While constructing our Spring bean class then it depends on HibernateTemplate. So we need to configure the Spring bean class like the following
The following example is for integrating Spring bean with hibernate.
Table: Syntax: create table employee (eno number(10) primary key, ename varchar2(30), address varchar2(100))
Employee.java
NARESH i technologies
SPRING
SUDHEER
EmployeeDao.java
EmployeeDaoImpl.java
NARESH i technologies
SPRING
SUDHEER
Orm.xml
NARESH i technologies
SPRING
SUDHEER
ORMClient.java
NARESH i technologies
SPRING
SUDHEER
Output
Direct Integration from Spring to Hiberante
It is also possible to integrate the Spring and hibernate by directly importing hibernate
API into Spring bean. While using direct hibernate into Spring bean than the SesssionFactory of hibernate
should be made as singleton by the programmers. Inorder to make the SessionFactory as singleton in a Spring bean then we must add init
and destroy methods to Spring bean class. Either we can implement our bean class from InitializingBean and DisposableBean interfaces or we can include one method for initialization and other method for destroy. NARESH i technologies
SPRING
SUDHEER
If we add our methods for initialization and destroy then we have to inform the Spring IoC container by adding init-method and destroy-method attributes for the bean element. Code Snippet 1:
Spring AOP
NARESH i technologies
SPRING
SUDHEER
Introduction
We are aware that nowadays the most widely used methodology for developing enterprise applications is Object oriented programming (OOP).The OOP methodology was introduced in the 1960s to reduce the complexity of the software and improve its quality. This achieved by modularization and reusability. This allow developers to view the Software as a collection of objects that interact with each other, allowing easy
solving of critical problems and developing reusable units of software While implementing business logic for the real time applications we need not only the
business logic but also some services to it, to make it as enterprise logic. While implementing the business logic in the business methods we can combinable
implement both the logic and its required services into the business methods. In order spring framework the services that are overlapping on the business logic are
called as ‘cross-cutting’ concerns or ‘cross-cutting’ functionalities. Example
If combinable implement the business logic and the required services then there are some drawbacks a. The services and the business logic in each method, increases the size of a Java Class. Therefore complexity increases. b. If the same services are required in another business method then we cannot reuse those services and in each method separate implementations are required. NARESH i technologies
SPRING
SUDHEER
c. If any changes in some service in one method then that changes does not impact on
same services of another method. d. Selecting services dynamically at runtime is not possible. In order overcome the above problems we need to separate the business logic and the service. We can call this separation of the business logic and cross-cutting functionality as aspect oriented programming.
Authentication
Login
Transaction
The AOP the business logic and cross cutting functionality are implemented separately and executed at runtime as combinable.
Aspect Oriented Programming (AOP)
Aspect Oriented Programming (AOP) is a programming methodology that allows the developers to build the core concerns without making them aware of secondary requirements by introducing aspects that encapsulate all the secondary requirements logic and the point of execution where they have to be applied.
Terminology
Aspect: NARESH i technologies
SPRING
SUDHEER
a. Aspect represents or denotes a cross-cutting functionality. b. One real time service is required for a business logic called one aspect. c. An aspect denotes only the cross cutting functionality but not its implementation. Advice: a. Advice defines what needs to be applied and when b. The implementation of an aspect is called as an Advice c. An Advice provides the code for implementation of service. JoinPoint a. JoinPoint is where Advice is applied. b. While executing the business logic of a business method, the additional services are needed to be injected at different places/points we call such points as JoinPoint. c. At a JoinPoint, a new service will be added into the normal flow of a business method. d. In the execution of a business method, the services are required at the following
three places. We call them as the three Join Points. i. Before Business logic of a method states ii. After Business logic of a method is completed. iii. If the business logic throws an exception at runtime. Pointcut a. Pointcut is the combinations of different Joinpoints where the advices need to be applied. (or) A Pointcut defines what advices are required at what Joinpoints. b. All business methods of a class does not required all services. Introduction a. An Introduction adds new properties and new methods to already existing classes at runtime by without making any changes to the class. b. An Introduction introduces new behavior and a new state to the existing class at
runtime. Target a. A target is a class which is going to be advised a target class is nothing but a class
which is not yet added with AOP feature. It means a target is ‘PRE AOP OBJECT’. Proxy a. A proxy denotes an object that is applied with AOP feature. An object at PRE-AOP
called as target and a object at POST-AOP stage is called as a Proxy. Weaving a. Weaving is the process of applying advices to a target object to get a new proxy object. b. Though weaving process a target object will converted to proxy object, by adding advices. c. Weaving Process Types NARESH i technologies
SPRING
SUDHEER
i. Compile Time weaving is a process of injecting byte code of advice is applied on JoinPoint at compile time. ii. Class Loader Weaving is a process of injecting byte code of advice is applied on JoinPoint a Class Loading time. iii. Runtime weaving (Spring way) In this, target bean will be shielded with proxy bean and created by spring framework. Whenever Caller invokes methods on target bean then spring frameworks invokes proxy bean and then understand what advices methods need to be applied on target bean and executes real method of target bean along with their advices.
Advisor (or) Pointcut Advisor: An advisor advising advices to various Joinpoints we call advisor has a pointcut advisor. We have two types of Advisor. NARESH i technologies
SPRING
SUDHEER
Advice API:
Advice is an object that includes API invocation to systemwide concerns representing the action to perform at a joinpoint specified by pointcut. The different types of advices that Spring AOP framework supports are: i. Before advice: The advice that executes before the joinpoint. ii. After returning advice: The advice that executes after the joinpoint execution completes normal termination. iii. Throws advice: The advice that executes after the joinpoint execution if it completes with abnormal termination. iv. Around advice: The advice that can surround the joinpoint providing the advice before and after executing the joinpoint even is controlling the joinpoint invocation.
Before Advice
The before advice is the advice that executes before the joinpoint.That means this type of advice allows us to intercept the request and apply the advice before the execution of
joinpoint. In order to create a BeforAdvice our class should implement MethodBeforeAdvice
interface. MethodBeforeAdvice is an interface given in org.springframework.aop package. The org.springframework.aop.MethodBeforeAdvice interface has only one method
with following signature. For Example
NARESH i technologies
SPRING
SUDHEER
a. The first parameter Method is a class of java.lang.reflect package and this parameter is used to access the name of the business method through getName(). b. The second parameter Object [] args is used to access the parameters of the business method.The parameters are given to the before() method by the
container in the form of an Object [] args. c. The Third parameter is an object to whom this service is going to apply. The before() method can encapsulate the custom code that has to execute before the
joinpoint executes. The following diagram shows a sample sequence diagram explaining the operations when before advice and joinpoint execution terminates normally.Moreover,if this advice decides to discontinue the joinpoint execution then it can throw some exception. But if the before advice throws an exception, apart from terminating the further execution of
NARESH i technologies
SPRING
SUDHEER
the interceptor chain, the client is throw with exception, not a normal termination
Client
Proxy
Before Advice1
BeforeAdvice2
BeforeAdvice n
Target
1 : some Method()
2 : before()
3 : before()
4 : before()
5 : some Method()
7 : ()
6 : ()
The following sequence diagram describing the operations when before advice execution terminates abnormally, that is, throwing exception.
NARESH i technologies
SPRING
SUDHEER
Client
Proxy
Before Advice1
BeforeAdvice2
BeforeAdvice n
Target
1 : some Method()
2 : before()
3 : before() 4 : ()
5 : ()
As shown in figure, in the case where before advice throws an exception then an exception is thrown to the client without continuing further the interceptor’s execution and target object method.
NARESH i technologies
SPRING
SUDHEER
The following diagram describing the exception handling done by proxy when advice throws an exception.
NARESH i technologies
SPRING
SUDHEER
b. AccountService.java : This Interface have two abstract methods performing withdraw and deposit methods.
NARESH i technologies
SPRING
SUDHEER
c. AccountServiceImpl.java
d. AccountDao.java
NARESH i technologies
SPRING
SUDHEER
e. AccountDaoImpl.java
f. MyException.java
NARESH i technologies
SPRING
SUDHEER
g. LoggingAdvice.java
h. log4j.properties
NARESH i technologies
SPRING
SUDHEER
i. applicationContext.xml
NARESH i technologies
SPRING
SUDHEER
j.
k. Client.java
Output:
sudheer.html
After Returning Advice
The after returning advice is the advice that executes after the joinpoints invocation
completes with normal termination. This advice has to be a subtype of org.springframework.aop.AfterReturningAdvice
interface. The org.springframework.aop.AfterReturningAdvice interface has only one abstract method.
NARESH i technologies
SPRING
SUDHEER
Syntax
Where the first parameter contains return value of the business method or null.
If a business method return type is void then the return value contains null
In this afterReturning advice, we can access the return value. But we can not modify this return value.
Example: see class room example
NARESH i technologies
SPRING
SUDHEER
Throws Advice:
The throws advice is the advice that executes after the joinpoints invocation completes
with an abnormal termination. This advice has to be a subtype of org.springframework.aop.ThrowsAdvice interface. The org.springframework.aop.ThrowsAdvice is a marker interface and does not declare
any methods. This type of advice should implement one or more methods with the following method
signature. The throws advice can listen for the exceptions thrown by the method invoked on the target object but not the exceptions thrown by the advices configured for the target
object. The throws advice can handle the exception but it cannot stop the exeception throwing to the client. Syntax
The afterThrowing() method can encapsulate the exception handling logic like in an instance when an ArthimeticException is thrown we want to prepare a relevant message and send an email to the administrator. NARESH i technologies
SPRING
SUDHEER
SequenceDiagram
Example – see class room example
Around Advice:
Around advice is the combination of both before and After advices. In a single advice it is possible to implement both before and after services.
NARESH i technologies
SPRING
SUDHEER
Around advice is not given by Spring AOP and it is an opensource implementation call
AOP Alliance. Around Advice can be used by any framework which is supporting AOP. To create around advice, our class should implement an interface called
MethodInterceptor. In Around Advice, we implement before and after services in a single method called invoke().In order to separate before and after services and to execute business logic of
the method in the middle, we call proceed(). Syntax
The org.aopalliance.intercept.MethodInvocation allows us to get the details of the
invoked method of the target object, method arguments, and Joinpoint. The MethodInvocation interface extends invocation, which is a subtype of joinpoint.
NARESH i technologies
SPRING
SUDHEER
Class Diagram
The invoke() method implemented in around advice can call the proceed() method on
the given MethodInvocation object. The code that has to execute before the joinpoint execution has to be written before calling proceed() method and the code to execute after the joinpoint execution has to be
written after the procedd() method. Sequence Diagram:
NARESH i technologies
SPRING
SUDHEER
NARESH i technologies
SPRING
SUDHEER
Spring Web MVC Framework MVC Architecture
N-Tier architecture refers to the architecture of an application that has at least three
tiers separated logically or physically. This architecture model allows us to design application with any number of tiers
arranged above another. N-tier architecture is important because each tier in this can be located on physically
different servers. In case of applications that present a large amount of data to the user, it is recommended to separate data and user interface concerns so that changes to the user interface will not affect data handling, and that the data can be recognized without
changing the user interface. The Model-View-Controller pattern solves this problem by decoupling data access and business logic from data presentation and user interaction, by introducing an
intermediate component controller. The responsibilities of Model, View and Controller as defined under the MVC pattern are: Model: This tier is responsible to represent business process and business data of application. View: This tier is responsible to prepare the presentation for the client based on the outcome of request processing. That is, this renders the model data into client’s user interface type. Controller: This tier is responsible for controlling the request to response flow in the middleware.
MODEL-1 ARCHITECTURE
In this model, the client directly accesses the pages in the web container, and these
pages service the entire the request and response back. While servicing the client requests these pages generally use a model which represents
the business logic for the application. These pages are usually implemented using JSP pages, sometimes Servlets, and model as Beans.
NARESH i technologies
SPRING
SUDHEER
In this architecture, controlling and presentation are mixed into a single component, and hence this model architecture is also known as page-centric architecture.
Client
1 Request
(Browser)
5
Controller and Presentation (JSP) 4
2
Model (Java Bean)
3
DataStore (DB)
Model1 Architecture
MODEL-2 ARCHITECTURE
Front Controller Design Pattern:
NARESH i technologies
SPRING
SUDHEER
We know that patterns are strategies that allow programmer to share knowledge about
the recurring problems and their solutions. Documenting patterns is one way we can reuse and possibly share information on how
best it is solve to solve a specific problem. And a well-known definition for a pattern: A pattern is a tree-path rule, which express a
relation between a certain context, problem, and Solution. Context we have decided to use Model-View-Controller(MVC) pattern to separate the user interface logic from the business logic of web application. We have reviewed the Page Controller pattern,but page controller classes have complicated logic, or our application determines the navigation between pages dynamically based on configurable
rules. Problem: we want to structure the controller for very complex web application in the best possible manner so that we can achieve reuse and flexibility while avoiding code
duplication and decentralization problems in page controller. Forces The following are the characteristics of the forces from the MVC that applies the Front Controller pattern: a. If common logic is replicated in different pages in the system, we need to centralize this logic to reduce the amount of code duplication. Removing the duplicated code is critical in improving the overall maintainability of the System. b. We want to separate system processing logic from View. c. The Page Controller pattern describes a separate controller per logical page. This solution breaks down when you need to control or coordinate processing across
multiple pages. Solution Use a Front Controller as the initial point of contact for handling all related requests. The Front Controller solves the decentralization problem present in Page Controller by channeling all requests through a single controller that is, it centralizes control logic that is otherwise duplicated, and even manages key request handling activities, like protocol handling, context information, navigation and routing, and dispatch. Protocol Handling is a process of handling a protocol-specific request, which involves in resolving the request given in a specific protocol format and preparing a message in a specific protocol format.
NARESH i technologies
SPRING
SUDHEER
Context Transformation is a process of converting the protocol specific data into a more general form, like into our system-defined java bean object or into a general collection object. Navigation is a process that chooses the object for handling a particular request that can perform the core processing for this request and the view that can present the response to the client. Dispatch involves in dispatching the request from one part of the application to another, like from request handling object to view processing components. SPRING MVC FRAMEWORK
Spring Web MVC Framework is an open-source web application framework which is a
part of Spring Framework licensed under the terms of the Apache License, Version 2.0 . Spring Web MVC is one of the efficient and high-performance and high-performance
open-source implementation of Model-2 based Model-View-Controller (MVC). Spring Web MVC framework provides utility classes to handle many of the most
common tasks in Web application development. What is a Framework? Framework is a set of well-defined classes and interfaces that provides services to our application.
BENEFITS OF USING SPRING FRAMEWORK
Spring provides a very clean division between controllers, JavaBean models, and views. Spring's MVC is very flexible. Unlike Struts, which forces your Action and Form objects into concrete inheritance (thus taking away your single shot at concrete inheritance in Java), Spring MVC is entirely based on interfaces. Furthermore, just about every part of the Spring MVC framework is configurable via plugging in your own interface. Of course
we also provide convenience classes as an implementation option. Spring, like WebWork, provides interceptors as well as controllers, making it easy to
factor out behavior common to the handling of many requests. Spring MVC is truly view-agnostic. You don't get pushed to use JSP if you don't want to; you can use Velocity, XLST or other view technologies. If you want to use a custom view mechanism - for example, your own templating language - you can easily implement the Spring View interface to integrate it. NARESH i technologies
SPRING
SUDHEER
Spring Controllers are configured via IoC like any other objects. This makes them easy to
test, and beautifully integrated with other objects managed by Spring. Spring MVC web tiers are typically easier to test than Struts web tiers, due to the avoidance of forced concrete inheritance and explicit dependence of controllers on the
dispatcher servlet. The web tier becomes a thin layer on top of a business object layer. This encourages good practice. Struts and other dedicated web frameworks leave you on your own in implementing your business objects; Spring provides an integrated framework for all
tiers of your application. It provides a rich functionality for building robust Web Applications. The Spring MVC Framework is architected and designed in such a way that every piece
of logic and functionality is highly configurable. Spring can integrate effortlessly with other popular Web Frameworks like Struts,
WebWork, Java Server Faces and Tapestry. Spring is not tightly coupled with Servlets or JSP to render the View to the Clients. Integration with other View technologies like Velocity, Freemarker, Excel or Pdf is also
possible now. In Spring Web MVC you can use any object as a command or form-backing object; you
do not need to implement a framework-specific interface or base class. Spring’s data binding is highly flexible: for example, it treats type mismatches as validation errors that can be evaluated by the application, not as system errors. Thus you need not duplicate your business objects’ properties as simple, untyped strings in your form objects simply to handle invalid submissions, or to convert the Strings properly. Instead, it is often preferable to bind directly to your business objects.
SPRING MVC ARCHITECTURE The following diagram describes the architecture and lifecycle of Spring MVC Framework.
NARESH i technologies
SPRING
SUDHEER
Following is the Request process lifecycle of Spring 3.0 MVC:
o The client sends a request to web container in the form of http request. o This incoming request is intercepted by Front controller (DispatcherServlet) and it will then tries to find out appropriate Handler Mappings. o With the help of Handler Mappings, the DispatcherServlet will dispatch the request to appropriate Controller. o The Controller tries to process the request and returns the Model and View object in form of ModelAndView instance to the Front Controller. o The Front Controller then tries to resolve the View (which can be JSP, Freemarker, and Velocity etc) by consulting the View Resolver object. o The selected view is then rendered back to client. COMPONENTS OF SPRING MVC FRAMEWORK
The following components are part o Spring MVC Framework 1. Dispatcher Servlet 2. Handler Mapping NARESH i technologies
SPRING
SUDHEER
3. ModelAndView 4. ViewResolver 5. Controller DISPATCHERSERVLET
The DispatcherServlet of Spring Web MVC framework is an implementation of Front Controller and is a Java Servlet component, that is, it is a Servlet Front for Spring Web
MVC applications. DispatcherServlet is the front controller class, that receives all incoming HTTP Client
requests for the Spring Web MVC application. In addition, DispatcherServlet is responsible for initializing the Spring Web MVC framework for our application, and is a Servlet implemented as a subtype of HttpServlet
just like any other Servlet. DispatcherServlet is also required to be configured in our web application like any other
Servlet, that is, into Web application deployment descriptor. The following Code snippet shows the declaration of DispatcherServlet in web.xml. Code Snippet
The preceding code snippet shows the declaration of DispathcerServlet. In addition to this declaration we can configure the initialization parameters to alter the behavior of the DispatcherServlet with respect to locating the Spring Bean XML
configuration files and initializing the application context. The following code snippet shows the declaration of DispatcherServlet configured with a ‘contextConfigLocation’ init parameter described.
NARESH i technologies
SPRING
SUDHEER
The preceding code snippet declares DispatcherServlet that specifies the Servlet to use applicationBeans.xml and applicationControllers.xml documents to initialize
WebApplicationContext. DispatcherServlet has to be configured to receive all the requests to our application, that
is, for various services,DispatcherServlet’s mapping should be generic. The following code snippet shows the sample mapping for DispatcherServlet.
As per the mapping shown in the preceding code snippet all the request for this context whose servletPath ends with .spring extension are dispatched by the web container to the DispatcherServlet.
HANDLERMAPPINGS
NARESH i technologies
View more...
Comments