Você está na página 1de 47

Spring

Framework:Framework is the predefine way to do any specific task. Framework provides the
abstraction to reduce the complexity to do any specific task.
All the frameworks are represented by the set of API and the standard.
By using a framework any developer can focus only on to the actual requirement of
the client as framework provide the base for any type of work.
Spring Framework:
Spring is the java based open source, light weighted and loosely coupled that
provides the dependency injection and aspect oriented programming for all
kinds of java application such as standalone application, JEE application or any
other framework based application.

Spring is an open source because its library freely available on to the


internet.

Spring is the light weighted because the spring container is the light
weighted. Spring container can be activated by just creating the objects for
certain predefine classes.

Most of the spring application can be executed without the heavy weight
application server and web server. Thats why spring application requires the
less memory and CPU resources.

Spring framework is easy to learn.

Loosely coupled:
Spring is the loosely coupled framework because of the following reasons:

While working with spring we can use individual module or multiple modules
together.

We can integrate spring with the other java technologies in the application
development like servlet, JSP, struts, hibernate and etc.

Every spring module provide abstraction layer on the multiple core


technologies and makes the programmer free from the core technologies
based programming.

AOP (Aspect Oriented Programming):


AOP is the new concept in the spring. It is always recommended develop the large
scale application by enabling the middleware service like security, transaction
management etc.
Spring AOP methodology is use to apply middleware service on the spring
application.
Dependency Injection:Dependency injection is the term that always is compared with term dependency
lookup.
Dependency Lookup:
When any resource explicitly searches and gathered dependent values from other
resources. In dependency lookup the resource pulls the value from other resources.
For example getting the session object into the servlet by invoking the
request.getSession() this is the dependency lookup.

Dependency Injection:The underlying server or container or framework or runtime environment assign the
values through the resource automatically and dynamically is known as the
dependency injection. In dependency injection the underlying container or server,
runtime environment or framework which is the value into the resources. For
example in case of servlet in the service method the request and response object
injected by the servlet container.

MVC (Model View Controller):


MVC is the design pattern that is built upon the three tier architecture. In the MVC
where are the three layer Model, View and Controller. All the major projects are
based on the MVC architecture.
MModel-Business Logic + Presentation Logic(database Logic).
VViewPresentation Logic
CControllerIntegration Logic
Business Logic: Business logic is the main logic of application for example
calculating the interest on to the loan in the banking application.
Presentation Logic: presentation logic gives the user interface for the end user to
supply the input to the application and to view the result of the application.
Controller: controller contains the integration logic maintains the all the operation
of the application.

1- JSP(view)servlet(controller)java beans
component(model)Database.
2- JSP(view)servlet(controller)RMIcomponent(model)Database
3- JSP(view)servlet(controller)[ EJB session(business logic)+EJB Entity
Bean(persistence logic)](model)Database
4- JSP(view)servlet(controller)[ EJB session(business logic)+DAO
classes(JDBC code)(persistence logic)](model)Database.

DAO (Data Access Object): the java class that separate the persistence
logic from the other logic of the application to make the persistence logic as
the flexible logic and reusable logic is called the DAO(data access object).
5- JSP(view)servlet(controller)[ EJB session(business logic)+DAO
classes(JDBC code)(persistence logic)](model)Database
6- JSP(view)servlet(controller)[ EJB session(business logic)+DAO
classes(Hibernate)(persistence logic)](model)Database

7- Struts(view +controller) )[ EJB session Bean(Business


logic)+DAO(hibernate)(Business logic)](model)Database

8- Struts(view +controller) [spring JEE module(Business


logic)+DAO(hibernate)(persistence logic)](model)Database
9- Spring(view +controller)web module )[spring JEE module(Business
logic)+spring (ORM)/DAO module (hibernate)(persistence
logic)](model)Database

Points about the spring:


1. Type- java/JEE framework.
2. Vendor- Interface21.
3. Creator- Rod Johnson.
4. Open source software.
5. To download the spring- www.springframework.org
6. Version- 2.5, 3.x (compatible with 1.5 + onwards)
7. Spring documentation and FAQ (frequently ask question)www.springfamework.org .
8. Books- Spring In action- manning publication.
9. Spring 2.x contains the six modules.
10.

Spring 3.x contains the 20 modules but they are grouped into six

major modules.

Modules in the spring 3.X:

1. Spring

core module is the base module for all other module.

2. Spring DAO module provides the abstraction layer on the plain JDBC to
develop the persistence logic.

3. Spring ORM provides the abstraction layer from the other ORM such as
Hibernate, TopLink etc to develop the OR-mapping persistence logic.

4. Spring AOP module is given to apply middleware services (Aspects) on the


spring application.

5. Spring web module is given to make the spring application communicable


from other web frameworks software application like struts application and
JSF application.

6. Spring web MVC is given springs on web framework to develop the MVC
architecture based web application.

7. Spring context module/ JEE module provides the abstraction layer on the
multiple core technologies such as RMI, JMS, JNDI, java mail, EJB etc. to
develop the enterprise application and other application.

8. NOTE: the whole spring framework is built in the jar files.


9.

Spring.jar represents the whole spring API and its dependent jar files.

10.

Common-logging.jar is one of the dependent jar files class and

interfaces of the Spring.jar uses the classes and interfaces of the Commonlogging.jar.

11.

POJO and POJI programming models: all the latest technologies

and their latest version (released after 2005) are supporting the POJO/POJI
programming model to make the technologies and application light weighted.

12.

POJO class:

When the java classes taken as the resources of the application and not
extending and not implementing to the technologies specific class and API
and that java class is known as the POJO classes.
Example-

class Test

{
}
This is the POJO class.
class Test extends Thread
{
}
This is also a POJO class.

Class that extends to other class of the JDK library then it will be considering as
POJO.
class Test extends Serializable
{
}
Test is still POJO class.
class Test extends ABC
{
} ABC is technology specific class then test class will not be a POJO class.

POJI (Plain Old Java Interface):These are the interfaces that never extend to any technology specific interface.
1. interface Test
{
} (POJI)
2. interface Test extends Serializable
{
} (this is also POJI)
3. interface Test extends ABC
{
} (ABC is the technology specific interface that why Test is not POJI)

Features of the spring framework:


1. It supports POJO and POJI programming model.
2. It is light weight that means does not require the heavy weighted web server
and application server for executing.
3. It provides the abstraction layer on the multiple core technologies and
simplifies the application development.
4. It gives the built in middleware services and allows to work with server
managed and third party supply middleware services.
5. Provides the environments for to perform the unit testing on the application.
Unit Testing- if programmer testing on its own peace of code is called unit
testing.
6. Provides the built in plug-in to make spring application integrate with other
java technologies base application.
7. Spring allows developing all kinds of application like standalone, two-tier,
three-tier, n-tier distributed and web application etc.
8. Allows developing all kinds of logic like presentation logic, business logic,
integration logic and persistence logic etc.
9. Spring gives its own web MVC framework develops the MVC architecture base
web application.
10.

Support the integration with java and JEE technology and also with

other java base frameworks.

MODULE-1
Spring core module:
1. It is the base module for all the other modules of spring.
2. It gives light weight spring container called BeanFactory.
3. We can use this module to understand the spring bean life cycle management
and dependency injection.
Spring Bean:
It is a concrete java class either created by the developer according to the client
requirement. It can also be provided by the spring in their library. The spring bean
class must be configured in the spring configuration file. The java bean class can
act as the spring bean but every spring bean need not be a java bean.
Spring gives two build light weight container:1. BeanFactory container
2. ApplicationContext container
Container:It is a software application or a java class that can take care of the whole life cycle
of the recourses.
Container aquarium
Life cycle berth to dead
Resources fish

Spring containers are responsible to perform the spring bean life cycle
management and to perform the dependency injection on to the spring beans
object.

Inversion of control (IOC):


The inversion of control (IOC) is a technique that is used to implement the
dependency injection in spring.
Spring (IOC) inversion of control is the core of spring framework. The Inversion of
control manages java objects from their creation to destruction and makes them
loosely coupled.

IOC Container:
The container is responsible to instantiate, configures and assembled the objects.
The IOC container gets the information from the xml file and works accordingly.
The main task performs by the IOC container.
1- To instantiate the application class
2- To configure the object
3- To assembled the dependency between the objects
There are two type of IOC container
1- BeanFactory container
2- ApplicationContext container

Spring BeanFactory Container

This is the simplest container providing basic support for DI and defined by the
org.springframework.beans.factory.BeanFactory interface.

This module is provides the fundamental functionality of the spring


framework. In this module BeanFactory is the heart of any spring-based
application. The entire framework was built on the top of this module.
This module makes the Spring container.

The most commonly used BeanFactory implementation is the XmlBeanFactory


class. This container reads the configuration metadata from an XML file and uses it
to create a fully configured system or application.
The BeanFactory is usually preferred where the resources are limited like mobile
devices or applet based applications.

To activate the BeanFactory container in our application just create the


object of any implemented class of
org.springframework.bean.factory.BeanFactory interface

For example

XmlBeanFactory fact=new XmlBeanFactory(spring configuration file name)


XmlBeanFactory-implementation class of BeanFactory interface.

Spring ApplicationContext Container:


The Application context module makes spring a framework. This
module extends the concept of BeanFactory, providing support for
internationalization (I18N) messages, application lifecycle
events, and validation. This module also supplies many enterprise
services such JNDI access, EJB integration, remoting, and
scheduling. It also provides support to other framework.

ApplicationContext container is the enhancement of the bean factory


container and it is part of spring JEE/context module.
The most commonly used ApplicationContext implementations are:
1- FileSystemXmlApplicationContext: This container loads the definitions
of the beans from an XML file. Here you need to provide the full path of
the XML bean configuration file to the constructor.

ApplicationContext context = new


FileSystemXmlApplicationContext("beans.xml");
HelloWorld obj=(HelloWorld)context.getBean("helloWorld");

2- ClassPathXmlApplicationContext: This container loads the definitions


of the beans from an XML file. Here you do not need to provide the full
path of the XML file but you need to set CLASSPATH properly because this
container will look bean configuration XML file in CLASSPATH.
ApplicationContext appCtx =
new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld obj=(HelloWorld)context.getBean("helloWorld");
1- WebXmlApplicationContext: This container loads the XML file with
definitions of all beans from within a web application.

Spring core module application contents the following resources:


1. Spring interface (Java interface)
2. Spring Bean class (Java POJO class)
3. Spring Configuration file (xml file)
4. Spring client (java class with main())
Spring Interface:
1- It can be the POJI.
2- It is the optional recourse but recommended to have.
3- It contains the declaration of the business method (utility method) act as the
common understanding between the client applications and the spring bean
just like a course broacher having the declaration of the topic.(that act as the
agreement between faculty and student).
Spring Bean class:

1. It is the concrete java class configured in the spring configuration file.


2. Developer creates the spring bean class to prepare the business logic to full
fill the client requirements.
3. It implements to the spring interface.
4. It contains method constructer supporting the dependency injection.
5. It contains the business method.
6. It contains the lifecycle method.
7. It can be the POJO or the non POJO class.
8. It can be user defined or third party supplied or the predefined spring library
creates java class/java beans.

Spring configuration file:1. It is an xml file can be saving with any name.
2. We can have one or more spring configuration file in our application.
3. Spring beans must be configured in the spring configured file.
4. It contains the dependency injection/IOC related instructions.
5. Also contains the life cycle method configuration.
Client Application:1. Client application activates the spring container by creating the object of any
container class (BeanFactory of ApplicationContext).
2. Get the spring bean class bean object from spring container.
3. Call the business method on the spring bean class object.
Dependency injection implementation:Spring provide the three types of dependency injection.
1. Setter based injection. (By creating a setXxxx()).
2. Constructor based injection (by creating parameterized constructor).
3. Interface based injection (by implementation the interfaces).
NOTE: -

interface based injection always be used in special cases.

Setter Injection:If spring container calls the setXxx() method for automatically and dynamically
assigned the values to the properties of spring bean class services this is called the
setter injection.
Example:
Test.java:
package mypack;
//Bean class
class Test
{
//property of spring bean class.
String message;
//setter method to inject the value of message property by
the container
public void setMessage(String message)
{
this.message=message;
}
//Business method
public void showMessage()
{
System.out.println(message+" to all");
}
}

Beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans2.5.xsd">
<bean id="t1" class="mypack.Test">
<property name="message" value="Good Morning"/>
</bean>
</beans>

t1-

is the name of the reference variable of the bean object.

<property> is used to specify the dependency injection in the bean object.


Testclint.java:
package mypack;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
import java.io.File;
public class TestClient
{
public static void main(String args[])
{
//File f=new File("beans.xml");
//String path=f.getAbsolutePath();
FileSystemResource resource=new FileSystemResource("beans.xml");
XmlBeanFactory factory=new XmlBeanFactory(resource);
Test t=(Test)factory.getBean("t1");
t.showMessage();
}
}

Constructor based injection:In this type injection the spring container uses the parameterized constructor to
create the spring bean class object and to assign the values to the bean properties
then it is called constructor injection.
Note: The setter injection takes place immediately after the spring bean class
object creation where as constructor injection takes place along with the spring
bean class object creation.
Example:
package mypack;
//Bean class
class Test
{
//property of spring bean class.
String message;
/* setter method to inject the value of message property by the
container */
public Test(String message)
{
this.message=message;
}
//Business method
public void showMessage()
{
System.out.println(message+" to all");
}
}

/****change in the configuration file***************/


<bean id="t1" class="mypack.Test">
<constructor-arg value="Good Morning"/>
</bean>

</beans>
Note:
1- Assigning the value of bean property with the constructor like msg=hello
gives the tight coupling between the bean property and its dependent value.
2- Assigning the value of the bean property by specifying the value in the spring
configuration file and it gives the loose coupling and perform the dependency
injection.
3- We can also pass the beans.xml directly into the arguments of the
constructor of the file system resource class.
FileSystemResource resource =new FileSystemresource (beans.xml);
4- In order to compile the TestClient.java there is requirement of the springbeans-3.2.1.jar and spring-core-3.2.1.jar. To run the TestClient the
common-logging-1.1.2.jar also must be included.
5- In the constructor base injection if there are more than one parameters then
we have to use the index attribute.
<constructor-arg index=0 value=good morning/>
6- In case of the setter based injection the default constructor of the bean class
will be invoked.
7- The dependency injection automatically will be performed on to the spring
bean object when it will be created by the spring core container. If the clients
creates the spring bean object then the dependency injection have to be
performed explicitly.
8- Naming convention:
Demo

Spring interface name.

DemoBean

Spring Bean class Name

Demo.cfg.xml Spring configuration file


DemoClient

Example:

Spring Client Application

/*------------Demo.java(Interface)----------------*/
package mypack;
interface Demo
{
String generateWishMessage();
}

/*------------DemoBean.java(Bean class)----------------*/
package mypack;
import java.util.Calendar;
public class DemoBean implements Demo
{
String msg;
public DemoBean(String msg)
{
this.msg=msg;
}
public String generateWishMessage()
{
Calendar c=Calendar.getInstance();
int h=c.get(Calendar.HOUR_OF_DAY);
if(h<12)
return(msg+"------------Good morning:");
else if(h<=16)
return(msg+"------------Good After Noon:");
if(h<20)
return(msg+"------------Good evening:");
else
return(msg+"------------Good Night:");
}
}

/*------------Demo.cfg.xml(Configuration file)----------------*/

<?xml version="1.0" encoding="UTF-8"?>


<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="t1" class="mypack.DemoBean">
<constructor-arg index="0" value="Hello"/>
</bean>
</beans>
/*------------DemoClient.java(Spring Client application)------------*/

package mypack;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
import java.io.File;
public class DemoClient
{
public static void main(String args[])
{
//File f=new File("beans.xml");
//String path=f.getAbsolutePath();
FileSystemResource resource=new
FileSystemResource("beans.xml");
XmlBeanFactory factory=new XmlBeanFactory(resource);
DemoBean t=(DemoBean)factory.getBean("t1");
System.out.println(t.generateWishMessage());
}

Note:When the constructer injection and setter injection both are performed in the spring
configuration file for the spring bean object then first of all constructer injection will
be perform and then the setter injection will be perform.

If use Constructor injection we have to inject dependence at time bean create.


If use Setter injection we can injection later.
Setter Injection

Constructor Injection

1. In Setter Injection, partial injection of

1. In constructor injection, partial

dependencies can possible, means if we

injection of dependencies cannot

have 3 dependencies like int, string, long,

possible, because for calling

then its not necessary to inject all values if

constructor we must pass all the

we use setter injection. If you are not inject

arguments right, if not so we

it will takes default values for those

may get error

primitives
2. Setter Injection will overrides the

2. But, constructor injection

constructor injection value, provided

cannot override the setter

if we write setter and constructor

injected values.

injection for the same property.

3.If we have more dependencies for


example 15 to 20 are there in our bean
class then, in this case setter injection is not
recommended as we need to write almost
20 setters right, bean length will increase.

3. In this case, Constructor


injection is highly recommended,
as we can inject all the
dependencies within 3 to 4 lines

4. Setter injection makes bean class object

4.Constructor injection makes

as mutable.

bean class object as immutable

5. If we have number dependencies, at that

[We cannot change ]

time setter injection is not recommended as

5. In case of Constructor

it increases length of bean class.

injection more number


dependencies it can be handle
with one constructor.

Bean collaboration: -If one bean class is holding another spring bean class Object
then it is called the bean collaboration.
To inject the one bean into another then we have to use the <ref> tag in the
spring configuration file.

Example:
/*------------TestBean.java----------------*/

package mypack;
class TestBean
{
String msg;
public void setMsg(String msg)
{
this.msg=msg;
System.out.println("Setter message Testbean performed:");
}
public String toString()
{
return("Welcome & "+msg);
}
}

/*------------DemoBean.java(Bean class)----------------*/
package mypack;
interface Demo
{
String sayHello();
}

package mypack;
import java.util.*;
class DemoBean implements Demo
{
int age;
Date dt;
TestBean tb;
public void setAge(int age)

{
System.out.println("Set age in the DemoBean:");
this.age=age;
}
public void setDt(Date dt)
{
this.dt=dt;
}
public void setTb(TestBean tb)
{
this.tb=tb;
}
public String sayHello()
{
return(tb+"\n Date of joining "+dt);
}
}

/*------------Demo.cfg.xml(Configuration file)----------------*/

<?xml version="1.0" encoding="UTF-8"?>


<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="date" class="java.util.Date">
<property name="date" value="02"/>
<property name="month" value="08"/>
<property name="year" value="114"/>
</bean>
<bean id="tbean" class="mypack.TestBean">

<property name="msg" value="Good evening"/>


</bean>
<bean id="d1" class="mypack.DemoBean">
<property name="age" value="25"/>
<property name="dt" ref="date"/>
<property name="tb" ref="tbean"/>
</bean>
</beans>
/*------------DemoClient.java(Spring Client application)------------*/
package mypack;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
import java.io.File;
public class DemoClient
{
public static void main(String args[])
{
//File f=new File("beans.xml");
//String path=f.getAbsolutePath();
FileSystemResource resource=new
FileSystemResource("beans.xml");
XmlBeanFactory factory=new XmlBeanFactory(resource);
DemoBean t=(DemoBean)factory.getBean("d1");
System.out.println(t.sayHello());
}
}
Note: - The toString () method of the TestBean will be invoked when the TestBean
object is placed in the return statement in the sayHello() method in the DemoBean
class.
When we concat any reference variable with the String constant then internally
automatically the toSting() will be invoked.

Note: - The value attribute in the <property> tag will be used to inject the
primitive type and string type values <ref> attribute is used to inject the reference
type property.
Alternatively we can also use the <value> and <ref> tags.
changes in the cfg file:<bean

id=d1 class=DemoBean>

<property name=age>
<Value>25</value>
</property name=dt>
<ref bean=date/>
</property>
<property name=tb>
<ref bean=tbean/>
</property>
</bean>
</beans>
To configure the different type of dependent values in the configuration
file.
Property type

tag/attribute

1. Primitive and String

<value>/value attribute

2. Array

<list>

3. Java.util.List

<list>

4. Java.util.Set

<set>

5. Java.util.Map

<map>

6. Beantype

<ref>/ref attribute

7. Java.util.property

<props>

8. To assign the null value

<null> tag

Creating the spring bean that have the all type of properties:-

Note:- In case of java.util.map type property key and value can be any primitive,
string or any java object.
In case of java.util.properties type property the key and value must be the
string.

Spring Bean Scopes


Spring framework supports five types of scopes and for bean instantiation as of
Spring 3.0 and also we can create a custom scope.
1.
2.
3.
4.
5.

I.

singleton
prototype
request
session
global_session

singleton scope:
The container creates only one object of spring bean class even though the
factory.getBean() method is called for multiple times with same bean id.

<bean id="..." class="..." scope="singleton">


--------------------------------</bean>
Return a single bean instance per Spring IoC container.

II.

prototype scope:
The container creates multiple objects for the one spring bean class for the
multiple times of the factory.getBean() method is called.

<bean id="..." class="..." scope="prototype">


-----------------------------------------</bean>
III.

request scope:
The container keeps the spring bean class object as the request attribute in
the web application.

<bean id="..." class="..." scope="request">


-----------------------------------------</bean>
Return a single bean instance per HTTP request
Request-scoped beans are created each time an HTTP request makes its way
into a servlet resource that is injected with one.

IV.

session scope:
The container keeps the spring bean class object as the request attribute in
the web application.

<bean id="..." class="..." scope="session">


-----------------------------------------</bean>
Return a single bean instance per HTTP session
V.

Global sessionscoped beans are applicable only in the context of portlet


applications.

Note: Singleton will be the default scope. The java class that allows us to
create one java object per JVM is called singleton java class.

Wiring:
Performing a dependency injection on the bean property is called wiring. There are
two types of wiring.

Explicit wiring

Autowiring

1- Explicit wiring:
In this wiring the bean property will be configured explicitly for wiring by
using <property> tag or <constructor-arg> tag.
2- Autowiring :
In this wiring bean properties will not be configured explicitly but the
container automatically detects and injects the value into the bean property.
To enable the autowiring we need to use the autowire attribute of the
<bean> tag. It internally uses setter or constructor injection.
Limitation with the autowiring:

Autowiring can't be used to inject primitive and string values.

It works with reference only.

Autowiring may arise ambiguous situation towards the dependency injection.

Autowiring kills the readability the configuration file in the spring application.

Advantage of Autowiring:
If programmer misses the dependency injection of any important property
then that property can be injected by the environment automatically.
There are following autowiring modes that can be performed by the spring
container.

1) no It is the default autowiring mode. It means no autowiring bydefault.


2) byName :The byName mode injects the object dependency according to name
of the bean. In such case, property name and bean name must be same. It
internally calls setter method.

<bean id="dm" class="mypack.DemoBean" autowire="byName">

3) byType
The byType mode injects the object dependency according to type. So property
name and bean name can be different. It internally calls setter method.

<bean id="dm" class="mypack.DemoBean" autowire="byType">


4) constructor
The constructor mode injects the dependency by calling the constructor of the
class. It calls the constructor having large number of parameters.
<bean id="dm" class="mypack.DemoBean" autowire="constructor">
5) autodetect It is deprecated since Spring 3.

<bean id="a" class="org.A" autowire="autodetect"></bean>

Example:
Demo.java

package mypack;
public interface Demo
{
String sayHello();
}
TestBean.java---------------------------------------package mypack;
public class TestBean
{
String msg;
public void setMsg(String msg)

{
this.msg=msg;
}
public String toString()
{
return(msg);
}
}

DemoBean.java
package mypack;
public class DemoBean implements Demo
{
TestBean tb;
//default constructor
public DemoBean()
{
System.out.println("demoBean created");
}
//parametrized constructor
public DemoBean(TestBean t)
{
System.out.println("DemoBean created by using parameterized constructor : "+t);
}
//setter method invoked
public void setTb(TestBean tb)
{
System.out.println("TestBean 1 injected by using setter method: "+tb);
this.tb=tb;
}
public String sayHello()
{
return("Welcome: "+ tb);
}
}
MyMain.java
package mypack;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyMain
{
private static ApplicationContext ctx;
public static void main(String args[])
{
ctx = new ClassPathXmlApplicationContext("beans.xml");

DemoBean db=(DemoBean)ctx.getBean("dm");
System.out.println(db.sayHello());
}
}

byname:
<bean id="tb" class="mypack.TestBean">
<property name="msg" value="Good Evening"/>
</bean>
<bean id="dm" class="mypack.DemoBean" autowire="byName">
</bean>
</beans>
Output:
demoBean created
TestBean 1 injected by using setter method: Good Evening
Welcome: Good Evening

The must be the bean object with the <bean id=tb>.


If there is no bean configured with the id=tb then the bean object will be
created with the default constructor and dependency injection will not be
performed.
If in the configuration file there is the bean object with tb but of the
different type then IllegalStatementException generated by the spring
container.

byType:
<bean id="tb" class="mypack.TestBean">
<property name="msg" value="Good Evening"/>
</bean>
<bean id="dm" class="mypack.DemoBean" autowire="byType">
</bean>
Output:
demoBean created
TestBean 1 injected by using setter method: Good Evening
Welcome: Good Evening

Constructor mode autowiring:


bean id="tb" class="mypack.TestBean">
<property name="msg" value="Good Evening"/>
</bean>
<bean id="dm" class="mypack.DemoBean" autowire="constructor">
</bean>
</beans>
Output:
DemoBean created by using parameterized constructor : Good Evening
Welcome: null
It internally select the parameterized constructor of the DemoBean and pass the
t1 TestBean object as the argument.
Note: constructor autowiring mode internally uses the byType .
If there is more than one TestBean object configured the constructor mode of
autowiring will use the default constructor and will not perform the dependeny
injection.
If the bean class dose not contains the default constructor then the ambiguity
exception will be generated.
What happens if we configure the autowiring and explicit wiring both?

If we autowiring perform the setter injection and explicit wiring perform


the constructor injection then autowiring applicable.
If autowiring perform the constructor injection and explicit wiring perform
the setter injection the explicit wiring applicable.
If both perform the constructor injection then explicit wiring will be
affected.
If both perform the setter injection then explicit wiring will be applied.

Note:
Both type of container BeanFactory container and ApplicationContext
container support the autowiring.

Spring ORM Module


The spring ORM modules provide the wrapper on to the different ORM framework.
Plain JDBC and spring JDBC persistence logic will be develop by using SQL
queries and these SQL queries are database software dependent queries so this
persistence logic are database persistence logic.
To develop the object based database software independent persistence logic
without using SQL queries then we need to work with ORM software like Hibernate,
iBATIS, Toplink etc.
Spring ORM module does not supply its own ORM software but its provide the
abstraction layer on the existing ORM software and simplify the process of working
with the ORM software.

Hibernate and Spring Integration


In Hibernate framework, we provide all the database information hibernate.cfg.xml
file.
But if we are going to integrate the hibernate application with spring, we don't need
to create the hibernate.cfg.xml file. We can provide all the information in the
applicationContext.xml file.
Advantage of spring framework with hibernate
The spring framework provides HibernateTemplate class, so you don't need to
follow so many steps like create Configuration, BuildSessionFactory, Session,
beginning and committing transaction etc.
So it saves a lot of code.

org.springframework.orm.hibernate3.LocalSessionFactoryBean class
gives the SessionFactory object. Hibernate SessionFactory object represents
to the connection pool so we have to provide the Jdbc DataSource object by
the dependency injection.
Note: SessionFactory object is used to create the HibernateTemplate class
object.
Configuration of the bean in the applicationContext.xml file:
In this file, we are providing all the information of the database in the
BasicDataSource object. This object is used in the LocalSessionFactoryBean
class object, containing some other informations such as mappingResources and
hibernateProperties. The object of LocalSessionFactoryBean class is used in the
HibernateTemplate class.

<?xml version="1.0" encoding="UTF-8"?>


<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url"
value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>
<property name="password" value="oracle"></property>
</bean>
<bean id="mysessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="template"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>
<bean id="d" class="com.EmployeeDao">
<property name="template" ref="template"></property>
</bean>
</beans>

Important method of HibernateTemplate class:

save(--), persist(--): to insert the record.

update(--): update the record.

load(--), get(--): to select the record.

delete(--): to delete the record.

merge(--), svaeOrUpdate(--): for inserting or updating the record.

These method for single row operations.


Method for bulk operation:

bulkUpdate(--): for HQL based non select operation.

find(--), findXxx(--): for HQL based select based operation.

iterate(--): for HQL based select operation.

Spring Annotation
Annotations are the java statement and they are alternate for the xml file
based Meta data and resource configuration information.
Syntax for use the annotation:
@<annotation-name> (param1=value, param2=value)
Annotation-name: like the XML tag name.
param1, param2: like the xml attribute.
Difference between annotation and xml with aspect to represents the
information about the application.
XML file
1) XML parsers are the heavy

Annotation
1) Annotations are the java component

weighted program to read the

internally represented by the

information from the xml.

classes.

2) As the xml file is external from the


java program, if the information is

2) After changing the information


recompilation is necessary.

changed then no need to recompile


the program.
3) Through the xml meta data about

3) Only java based information can

the application can also be retrieved by

retrieved the information from the

the application of other technologies.

annotation

There are the two types of annotation:

Annotation for documentation: useful while generating the java API


documentation.
@Params, @Since, @Version, @ Author etc. introduce in the JDK 1.1.

Annotation for programming: useful for metadata and resource


configuration operation. @Override, @Deprecated, @Resource, @Autowired
etc.

All the java technologies that are designed based on jdk1.5+ supporting the
annotation based programming, Spring2.5+, Hibernate3.2+ struts2.X, EJB3.X,
servlet3.X and etc.
We can apply the annotation at three levels.

Resource Level- classes and interfaces.

Method Level- on the java method

Field Level-on the mapper variables.

Annotation in the spring library to configure the spring bean:1. @Component:


It makes the java class as the spring bean and auto detectable from the class
path.
2. @Service:
Same as the @Component but use for the service layer, spring beans
(containing the business logic).
3. @Repository:
Same as the @Component for the DAO type spring beans (containing
persistence logic).
Annotation to perform the dependency injection:1. @Value: To inject the simple values, Array values and List values.
2. @Resource: To Inject the values to the reference type bean property.
3. @Autowired: To enable the auto wiring on the bean properties.

Note: Still annotations are not ready to configure the dependent values for Map,
Set and properties type bean property.

In the spring environment bean generally used both xml file and annotations
together to perform the dependency injection.
If @Autowired annotation is placed on to the top of setter method then it is
go for setter based injection autowiring.
If @Autowired annotation is placed on to the top of parameterized
constructor then it is go for constructor injection based autowiring.
If @Autowired annotation is placed on to the top field then it goes for the
setter injection based autowiring.
org.springframework.stereotype package: This package provide the following
type annotation: @Service, @Component, @Controller, @Repository.
org.springframework.bean.factory.annotation package: This package provides
the following annotation: @Required, @Autowired, @Value, @Configurable.
Example:

public interface Test


{
public String sayHello();
}
/----------------------------------------------------------------------------------/
import java.util.*;
import org.springframework.stereotype.*;
import org.springframework.context.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
@Service
public class TestBean implements Test
{
Date d;
@Autowired
public void sayD(Date d)
{
this.d=d;
}
public String sayHello()
{

return("Good Evening :"+d);


}
}
/----------------------------------------------------------------------/
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.*;
public class TestClient
{
public static void main(String args[])
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
Test t=(Test)ctx.getBean("tb");
System.out.println(t.sayHello());
}
}
/----------------------------------------------------------------------------/
<?xml version="1.0" encoding="UTF-8"?>
<beans -----------<bean id="tb" class="my.TestBean"/>
<bean id="date" class="java.util.Date"/>
</beans>

AOP with Spring Framework


Aspect oriented programming (AOP):
Spring AOP is not related to the object oriented programming. OOP is the
methodology to create programming language and spring AOP is the
methodology applies to the middleware service on the spring application.
Middleware services are the additional services that are apply on the
application to make our application more perfect and accurate in all the
situation. Example of the middleware services:
1. Transaction management: Applies to everything or do nothing principle
on the given code
2. Security service: Protects the application from unauthorized user.
3. Logging service: Keeps track of application execution.
4. Connection pooling: Keeps the set of readily available JDBC connection
objects.
If we write code of middleware services directly in the application
middleware services code becomes specific to one application (no
reusability). More over the code of the middleware services may dominate
application code.
Spring application allows us to write the application code and middleware
services separately and allow linking the middleware services code with the
application through the xml file or annotation.

Due to this code of middleware services becomes reusable.

Application Module
Spring AOP terminology:
1. Aspect: It is the specification containing rules and guidelines to
implements the middleware services.
2. Advice: It is the real middleware service which is the implementation of
aspect.
3. Join Point: Possible positions in our business method where the advice
can be applied. For example beginning of the business method, ending of
the business method , business method returning value business closed
exception etc.
4. Pointcut: The XML or annotation based entry that links advices with join
point of business method.
5. Advisor: Advice + pointcut together is called advisor before applying
advice on business method it will be taken in the form of advisor object.

6. Wiring: Configuring the bean property or dependency injection is called


wiring.
7. Weaving: Applying the middleware services on spring bean class through
the aspect oriented programming is called weaving.
Spring AOP, AspectJ, support only the method level weaving that means
they does not support the field level weaving.
8. Target Bean (Target Object): Spring bean class object on which beans
are planning to applying middleware services is called target bean (target
object).
9. Proxy Bean (Proxy Object): spring bean class object on which the
middleware services are already applied is called proxy object.
Note:
I.

Business method called target method just executes the business


method.

II.

Business called on the proxy object executes the business method logic
along with middleware service.

Org.springframework.aop.framework.ProxyFactoryBean:
Generate the proxy object based on the given target object. There are four
types of advices:
1. Before Advice: Execute at the beginning of the business method
execution.
2. After Advice: Execute at the end of the business method execution.

3. Throw advice: execute when the exception is raised.


4. Around Advice: Execute at the beginning of the business method and
at the ending of the business method.
Note:
Using the spring AOP, AspectJ not only we can use spring or server
supplied middleware services we can also use to develop user define
middleware services and advices.
Step to develop Spring AOP based spring Application:
I.

Develop the java class as the advice class.

II.

Develop the spring bean interface and spring bean class having the
business method declaration and definitions.

III.

Develop the spring configuration file and configure the following beans.

Configure the spring bean class.

Configure the advice class

Configure the advisor class pointing to the advice class.

Configure the proxy factory bean specifying advisor and spring


bean.

Note:
The proxy factory bean class object gives the spring bean class object as the
proxy object.
VI.

Preparing the client:

Activate the spring container (BeanFactory or ApplicationContext


container).

Gather the business method on the proxy object.

Note: Business method called on the proxy object will be executed


along with middleware services (advices).
There are two types of advices:
1. NamedMatchMethodPointcutAdvisor: here the advice will be
linked with business method based on the names of the
business method.
2. RegexpMethodPointcutAdvisor: here the advice will be linked with
business method based on the regular expression.

Spring MVC

Você também pode gostar