Springs

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 58

SPRINGS

Why Spring?

 In j2ee application development, we got some component


technologies and servlet technologies.
 By using the component and service technologies of j2ee, we can
develop a good enterprise business app’s.
 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) JTS
5) JAAS (java authentication and authorization service)
6) JCA (java EE connector architecture)
 We use servlets and JSP technologies of J2EE for the development of
web application.
 We use EJB technology for the development and constructing of
Enterprise applications.
 While developing Enterprise application through EJB, we got the
following problems.
1) EJB component development requires multiple java files and xml files.
So, it makes burden on the programmer (or) developer.
2) EJB’s cannot run without out a container/ server. So, to test an EJB a
server is mandatory.
3) While testing an EJB, if it fails, then we need to shutdown the server
and after modification and once again we need to restart the server and
we need to test application. It is a time consuming process.
4) EJB’s are heavy weight components and having a lot of dependency with
the server.
 In order to overcome the above problems occurred at EJB, we got an
alternative for EJB technology as ‘Spring Frame Work’.
Note: Spring Frame work is not a replacement for EJB and it is just
alternative.
Before Spring:

Presentation layer Business

B.L D.A.L

View controller session Entity DB

Bean Bean

After Spring:

Presentation Business

View controller B.L D.A.L DB

Spring Hibernate

What is Spring FrameWork?

Spring is a lightweight and an open source frame work created by Rod


Johnson in 2003.
Spring is a complete and a modular Frame work. It means spring frame
work can be used for all layers implementation for a real time application
(or) spring can be used for the development of a particular layer of a real
time application.
Spring framework is said to be a non-intrusive framework. It means
spring framework does not force a programmer to extend (or) implement
their classes from any predefined class (or) interface given by Spring API.
In case of struts f/w. It will force the programmer that the programmer
class must extend from the base class provided by struts API. So, struts
we call them as invasive or intrusive frame work Spring is called light
weight component because of POJO model.
 Spring framework simplified J2ee application development by introducing
POJO model.
 Spring is important because of following 3 reasons.
1) Simplicity,
2) 2) feasibility,
3) 3) loose coupling.
 Spring provides simplicity , because of POJI/POJO interface Model.
 Spring is easy to test, because. Spring can be executed within a server and
even without a server.
 Spring provides loose coupling because of IOC (Inversion of control)
mechanism.
 Spring framework can be used to develop any kind of java application. It
means we can develop starting from a console application up to a
enterprise level application.
 Unlike other framework, spring framework has its own container.
So, spring works without server also.

Spring Modules:

In spring 1.x, the framework has divided into 7 well defined modules, but
in spring 2.x the framework is divided into 6 modules only.

i. Spring Core Module


ii. Spring Context (spring jee module)
iii. Spring DAO (spring jdbc ) module
iv. Spring ORM module.
v. Spring AOP module.
vi. Spring web mvc module.

Spring Modules Architecture:

SPRIING AOP SPRING SPRING SPRING

ORM JEE WEB

SPRING MVC

JDBC

Spring Core (IOC)

Spring Core:
Struts framework highlevel object is createdActionServlet

Hibernate highlevel object is created SessionFactory

Springframe work highlevel object is created BeanFactor

 This module provides the basic functionality required by a spring


application.
 Spring core module generates an high level object of the spring framework
called BeanFactory.
 Spring core module applies IOC/ dependency injection, for generating for
spring IOC container called as BeanFactory.
 All framework will follow a commonality called, an high level object is
created first and it will take care about low level objects required for the
application.

Struts Framework -> ActionServlet


Hibernate Framework -> Session Factory
Spring Framework -> BeanFactory.

Spring J2EE module: spring jee module is an extension to core module, where
core module creates container and jee module makes it as framework.

 Spring jee module acts real time services like e-mailing, jms, timer, jndi,
remoting, j18n, etc.., to this spring application.

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 (boilerplate code).

 The another advantage of this module is that we need to handle Exception


while working with the db because in spring all exceptions are Unchecked
Exceptions.

Spring ORM: This module is also to work with Database, spring ORM module
provides an abstraction layer on top of existing ORM tools.

When compared with spring DAO, Spring ORM module has two benefits.

a. Data transfer will be done in the form of objects.


b. ORM tools always throws unchecked exceptions.
 Even in ORM tools also, boilerplate code (or) repeated code is required. So,
in spring ORM module, spring framework has provided an abstraction layer
and this layer avoids the use of boiler plate code.
 By without using ORM module, spring can directly communicate with
iBATIS, JDO …etc.

 In a real time application, Business Logic need additional services.
 If we combine 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.
 To get out of the above problems , we got accept oriented programming in
spring.
 With AOP, Business logic and the required services both are separated.
Whenever service is required then it will be injected to the logic at run time.
 Spring AOP meaning is separation of business logic with its services is
required.

Spring web MVC:

 In this module, we do the following two operations.


a) We integrate our spring framework with outside mvc frameworks like
struts, JSF, …etc.,.
b) We can develop complete mvc application by without using any outside
framework.

SPRING CORE MODULE (SPRING IOC)


Tight coupling and loose coupling between objects:

 When developing java applications, generally one object will collaborate


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 there is a
coupling between two objects.
 In object to object collaboration, one object becomes dependent object and
the other object becomes caller object.
 For eg: if Traveler and Car are the two classes and Traveler object is called
dependent object and Car object is called caller object.
 When two classes are collaborating, if the first class is getting all the
required objects (dependencies) by itself then we call there is tight coupling
between the two classes (objects).

For example:

Class Traveller class car class whell

{ { {

Car c.newCar() wheel w.new wheel() void rotate()

Void startjourny() void move() {

{ { }

c.move(); logic w.rotate()

} }

} }

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 then there exists tight
coupling.
 According to the above example there is a tight coupling between
Traveler and Car object.
 If the method in Car class is changed from move() to run() then, in
Traveler class also the changes are required that is in startJournery()
instead of calling move(), we need to call run().

Eg:
class Traveller
{
Car c=new car()
Void starJourney()
{
C.run()
}
}

Class car

Void run()

 Tight coupling between object means, when two objects are


collaborating, if any changes are done on one object then the changes
are required on other object also.
 Loose coupling: In order to overcome tight coupling between objects spring
framework, uses dependency Injection mechanism.
 With the help of POJI/ POJO model and dependency Injection, it is possible
to achieve loose coupling.
 In the above example, Traveler and Car are tight coupled. If we want to
achieve loose coupling between the objects, Traveler and Car, we need to
rewrite the application like the following.

Eg

Class Traveller

Vehicle v;

Public void setV(Vehicle v)

This.v=v;

Public void startJourny()

v.move();
}

Interface Vehicle

Void move();

Public class Car implements Vehicle

Public void move()

System.out.println(“…………”);

Public class MotarBike implements Vehicle

Public void move()

System.out.println(“…………………………..”);

In the above example, through dependency Injection mechanism, Spring


container will initiate either Car object or MotorBike object into Traveler by
calling setter(). So, if Car object is replaced with MotorBike object then no
changes are required in Traveler class. It means there is a loose coupling between
Traveler Object and Vehicle Object.

Type 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 about object
creation and ________ the dependent of object required. As a programmer
we are responsible for only implementation of the business logic.
 There are two types of IOC a) Dependency lookup b) Dependency Injection.

Note: taking is called lookup and giving is called injection.

Eg: connection pooling in Servlet.

The servlet will go in to the pool and take the connection, this is called
Dependency lookup mechanism.

Whereas in spring, spring container will provide the object that means giving
the objects automatically this is called Dependency Injection.

as developer concentrating business logic but creating the objects.

Servlet
SOURCE

DATA

DS 3) pool

car 4) Con con con

con con

2) 1)lookup( )

Dependency Key/ds

Lookup JNDI Registory

mechanism

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 collaboration
objects automatically to the first object.
 In dependency lookup of IOC, the first object is responsible for obtaining its
collaborating objects from the container (or) repository etc.,

Eg: In servlet with connection pooling, servlet object depends on datasource


object. In this case nobody automatically gives data source object to servlet
object.

 Servlet itself goes to individual registry and takes DataSource object from
the registry by performing lookup operation as shown in above diagram.

Eg: 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 EJB object from it. It
means there is a dependency lookup.

Dependency Injection:

 In this type of, when one object is collaborating with another object, some
external person will be provide, the collaborate object to dependent object
automatically.
 In this type of IOC, the first object is not responsible to explicit take the
collaborating object required. It means the first object (dependent) does not
perform any lookup operation.
 In case of spring framework, the external person who performs dependency
Injection is called Spring IOC container.
 EJB3.x technology and spring framework both are supporting dependency
Injection type of IOC.

Class A {

B ab;

public A(B ab){} // constructor

public void setOb(B ab) //setter

This.ab = ab;
}

public void m1()

do.m2();

Class B {

Type of Dependency Injection:

1.Setter Injection
2.Constructor Injection
3.Interface Injection
 In spring framework, we use only setter and constructor injections, but not
interface injection.
 In struts 2.x, we have interface injection.

Setter Injection:

In this type of dependency Injection, the spring container, uses setter() in the
dependent class for injecting its dependencies (collaboration).

 Spring container knows whether to perform setter or constructor


injection, by reading the information from an external file called as
spring configuration file.
 In case of setter injection, the class must contain a setter () to get the
dependencies, otherwise spring container does not inject the
dependencies to the dependent object.

Eg: class A {

B ob;
public void setOb(B ob){

this.ob = ob;

public void m1() {

-----

------

Class B {

public void m2(){

------

 In the above class A is called dependent and class B is called ________ or


collaborator.
 In the dependent class there is a setter() for getting collaborate object. So
we called as setter injection.
 In spring framework, we call each class as a springBean. This spring bean
no way related with java bean.
 *** SpringBean and JavaBean are not same, because a java bean need a
public default constructor, but in spring bean sometimes we include
default constructor and sometimes we do not.
 In SpringBean classes, there is exist the following 3 types of dependency
values.
I. dependency in the form of primitive value. Eg: int k;
II. dependency in the form of object. Eg: FormBean fb;
III. dependency in the form of collection. Eg: List as;

Eg: public class TestBean{


private int x; //primitive

private SampleBean sb; //object

private List al; //collection

----

----

Dependency in the form of Primitives:

 The spring container understands whether dependency in the form of


primitive or not, whether setter or constructor injection is required..,etc.,
information by reading spring configuration file.
 Spring configuration file identified with any .xml
 If the dependency is in the form of primitive then we can directly provide in
the xml file for that property.

Eg: Class DemoBean {

int k;

public void setK(int k) {

this.k = k;

public void display() {

System.out.println(k);

Sprconfig.xml

<! DTD --- >

<bean>

<bean id=”id1” class=”DemoBean”>


<property name=”k”>

<value> 100 </value>

</property>

</bean>

 In spring configuration file, we used <property> element, so spring


container understands that there is a setter injection in the bean class.
 Inside <property> element, we have used <value> element. So spring
container understands that the dependency is in the form of primitives.
 In spring configuration file, we can use value as a sub element of property
tag or value, as an attribute of the property tag.

Eg: <property name = “k” value=”100” />

Note: If we pass a value from an xml file, then we can change that value whenever
it is required by without reopening our java code. It means we can directly modify
the value in xml file and we can run the java code by without any recompilation
of code.

Xml are used to change the value instantly.

Steps to write a spring cline application:

Step1:

a. spring environment start by loading spring configuration file into Resource


object.
b. We call this step1 as a bootstrapping of springframework.
c. Resource is an interface. ClasspathResource is an implementation class given
by springframework.
d. Both Resource interface and classpathResource are given
org.springframework.core.io package.
Syntax:
Resource res = new ClasspathResource(sfconfig.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 object and its 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.bean.factory.xml
package

Syntax:

BeanFactory factory = new XmlBeanFactory(res);

Step 3:

a. Get the Bean object from the spring container by calling getBean()
b. While calling getBean(), we need to pass the Bean Id as a parameter.

Step 4:

a. GetBean() always returns object. We need to typecast the object into our
spring bean type.
Object o = factory.getBean(“id”);
DemoBean db = (DemoBean)o;

Step 5:

Call the business method of the springBean by using the object.

db.display().

Spring Framework Installation:

 Working with a framework software is nothing but working with set of java
files given by that framework.
 If we want to use spring framework in a java client application then we
need to set the framework jar files into classpath.
 Spring framework is distributed as a combined jar file for all modules and
also individual jar files for each module.
 Spring framework is initially released by interface 2.1 and now it is
renamed as springsource.org
 Visit www.springsource.org and download spring framework 3.0.5 zip and
then extract it to get the jar files.
 The main jar file of spring is called spring.jar and it depends on
commons.logging.jar
 Spring.jar file exits e:\spring-framework-3.0.5\dist folder
 we can set individual jar files modules also into the classpath. These
modules jar file are available in
e:\ Spring-frameworks-3.0.5\dist\modules folder.
 Commons.logging.jar does not come along with spring framework and we
need to get separately.
 To work will all the modules of spring framework, we need to set the
following two jar files in the classpath.
1.spring.jar;
2.common-logging.jar

Strutsframework—craig r mcdanahan
Hibernate--- cravin king
Springframework – Rod Johnson

SpringTest1
welcomeBean.java
spconfig.xml
client.java
*.class

//welcome Bean.java
Public class WelcomeBean
{
Private string message;
public void setMessage(String message)
{
this.message = message;
}

public void show( )


{
System.out.println(“message”);
}

}
//springconfig.xml

<!DocType bean public -//SPRING//DTD BEAN 2.0 //EN”

http://www.springframework.org/dtd/spring-beans-2.0 dtd>

<beans>

<bean id=”id” class = “welcomeBean”>

<property name=”message”>

<value> welcome to spring framework </value>

</property>

</bean>

</beans>

//client.java

import org.springframework.core.io.*;

import org.springframework.beans.factory.*;

import org.springframework.beans.factory.xml.*;

class Client

Main ( )

Step-1

Resource res = new classpathResource(“spconfig.xml”);

Step-2

BeanFactory factory = new XmlBeanFactory(res);

Step-3

Object o = factory.getBean(“id”);
WelcomeBean wb = (WelcomeBean)o;

Step-4

wb.show();

1. Javac WelcomBean.java
2. set classpath = c:\spring.jar;c:\commons-logging-1.0.4.jar;%classpath%
3. client java
o/p w to SFW

Points to remember:

 In the above client application , when we called getBean(“id”), then


internally the spring framework or container executes the following
statements.
WelcomeBean obj = new WelcomeBean()
obj.setMessage(“welcome to springFramework”)
 By default each springBean (pojo) is a singleton class. Spring IOC container
will make a spring bean as singleton automatically.
 In the above client application, if we call getBean() by passing the same id
for multiple times, then multiple objects for the bean class are not created.
Instantiated the same object will be redeemed for multiple times.

Object o = factory.getBean(“id1”);
Object o1 = factory.getBean(“id1”);
Object o2 = factory.getBean(“id1”);
 In the above case, only one object of the WelcomeBean class created and it
is given for 3 times.
 The return type of getBean() is Object. Because getBean() is creating all
spring bean object. So, it returns the spring Bean object is returns
superclass reference as spring. Client programmer is type caste into
required Bean class type.
What is the difference between beanFactory and other Factory?

Beanfactory and other factory follows design pattern. It means the factory
produces objects. The difference is BeanFactory produces different Bean objects,
other factory always produces same type of objects.

Eg: In hibernate sessionFactory always produces Session Objects, where as


BeanFactory produces different Bean Class objects of the spring application.

Dependency in the form of objects:

 While constructing spring beans (pojo classes), one spring bean class
depends on another spring bean class, for performing some business
operation.
 If one bean class is depending on another bean class object, then we call it
as a object dependency.
 If one bean class is depending on another bean class object, then in spring
framework, the spring IOC container is responsible for creating and
initiating the dependencies.
 In spring configuration file, we have two ways to inform the container about
this object dependency.
a. By using inner beans.
b. By using <required> element.
 By using Inner Beans:
Inner bean needs 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 <bean> elements inside <property> in the xml.

For eg:

public Class DemoBean {


private SampleBean sb;
public SetSb(sampleBean sb)
{
this.sb = b;
}
public void m1( )
{
sb.m2();
}
}
SPconfig.xml:
<beans>
<bean id=”id1” class = “DemoBean” >
<property name = “sb”>
<bean class = “sampleBean”/>
</property>
</bean>
</beans>
 In the client application, if we call factory.getBean(“id1”) then internally the
springframework will do the following operations.
SampleBean obj1 = new sampleBean();
DemoBean obj2 = new DemoBean();
this.setSb(obj1);
 In the above example, DemoBean obj is depending on SampleBean object.
So, the spring container first created the SampleBean object and after that
the container created DemoBean object.
Drawback of inner Beans:
1. An inner bean doesn’t have any id. so, it is not possible to get that bean
object individually from the container.
2. If another bean class also depending on the same bean then in xml file,
again we need to add the inner bean definition.
SPconfig.xml
<beans>
<bean id="id1" class = "DemoBean">
<property name = "sb">
<bean class = "Sample Bean"/>
</property>
</bean>
<bean id="id2" class = "Example Bean">
<property name = "sb">
<bean class = "SampleBean"/>
</property>
</bean>
</beans>

 In order to overcome the above two problems of innerbeans, we need to use


<ref> element in the spring configuration file.

<ref> Element:
 When dependencies are in the form of objects then to inform the spring IOC
container, in spring-configuration xml file, we need to configure <ref> element.
 <ref> element is associated with either local or parent or bean attributes.
 When we add <ref> element then we need to pass id of collaborator bean to its
attribute, because the dependency is in the form of object.
Syntax:
<ref local/parent/bean = "id of collaborator bean"/>
= equal to
<ref local = "id of collaborator bean"/>
<ref local = " "/>
or
<ref local = " "/>
= is not equal to
<ref local="id of collaborated bean" parent="id of " bean= " id of collab "/>

 local: if local attribute is used with the <ref> element then the spring ioc
container will verify for the collaborator bean within the same container
(factory).
 In generally we try to configure all spring beans into a simple spring
configuration file, but it is not mandatory. Because, we can create multiple
spring configuration files also.
Eg:
public class DemoBean
{
private SampleBean sb;

public void setSB(SampleBean sb)


{
this.sb = sb;
}

public void m1()


{
sb.m2();
}
}

Spconfig.xml
<beans>
<bean id = "id1" class = "DemoBean" >
<property name = "sb">
<ref local = "id2" />
</property>
</bean>
<bean id = "id2" class "SampleBean">

</beans>

 In the above xml file, both the dependent bean and collaborator bean are
configured into the same xml file. It means into the same IOC container. So we
can use local attribute with <ref> tag.
 By loading this above xml file, we will get the spring IOC container object
called BeanFactory.

[ Resource res = new ClasspathResource(“spconfig.xml”),


BeanFactory factory = new xmlBeanFactory (res) ; or …………..]

 The above BeanFactory statement can also be written like the following.
BeanFactory factory = new XmlBeanFactory(res, nutt);
 The above xml configuration can also be created like the following:
spconfig.xml

<beans>
<bean id = "id1" class = "DemoBean" >
<property name = "sb">
<ref local = "id2" />
</property>
</bean>
</beans>
------------
-----------
test.xml

<beans>
<bean id = "id2" class "SampleBean">

</beans>

 In the above xml files, dependentBean is configured in spconfig.xml and


sampleBean is configured in the test.xml
 In the client application, we can load both xml files to get BeanFactorie.
 In spring IOC it is possible to create parent and child factories.
For Eg:
[ Resource res1 = new ClasspathResource(“test.xml”);
BeanFactory factory = new xmlBeanFactory (res1); ]

Resource res2 = new ClasspathResource(“spconfig.xml”);


BeanFactory factory2 = new xmlBeanFactory(res2, factory1);

 In the above factory2 is a child container of factory.


 Dependent bean is available in factory2 (child container and collaborator bean
is available in factory(parent container)). It means the both dependent bean
and its collaborator bean are not available in same container, so we can’t use
local attribute with, <ref> element.
 <parent> element:
 If <parent> attribute is used with <ref> element then the spring IOC container
will search for the collaborator bean all way at <parent> container but not in
the same container.
Eg:
config.xml

<beans>
<bean id = "id1" class = "DemoBean" >
<property name = "sb">
<ref parent = "id2" />
</property>
</bean>
</beans>
------------
-----------
test.xml

<beans>
<bean id = "id2" class "SampleBean">

</beans>
In the above xml files, ____ bean is available is available in factory2 and
collaborate bean is available .
 So <parent> attribute gettable with <ref> element.
 In parent and child factories, the names are given like parent and child, but it
is not possible to get parent factory bean object through child factory.
Eg: Ojbect o = factory.getBean(“id2”);
 The above statement is wrong because id2 is related factory (parent).

<bean>
 If this attribute is used with <ref> 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.

springconfig.xml

<beans>
<bean id = "id1" class = "DemoBean" >
<property name = "sb">
<ref parent = "id2" />
</property>
</bean>
</beans>
------------
-----------
test.xml

<beans>
<bean id = "id2" class "SampleBean">

</beans>

According to xml <bean> attribute working like parent.

Parent

Note: 1. While using <ref> element, if the given id is not found then null will be
assigned to the object, but an exception is not thrown.
2. If id is found, but the class is not a soutable for the required type then an
exception will be thrown by spring IOC container. The exception name is
org.spring-framework.beans.unsatisfiedDependencyInjectionException.
 The following spring application is to achieve lose coupling b/w objects. B/w
traveler and vehicle.
 In this example we are creating spring beans in the form of interface and
implementation class i.e poji/pojo model.

// Journey.java
public interface Journey
{
void startJourney();
}

//Traveller.java
public class Traveller implements Journey
{
private Vehicle v;
public void setV(Vehicle v)
{
this.v = v;
}
public void startJourney()
{
System.out.println("Journey started:");
v.move();
}
};

// Vehicle.java
public interface Vehicle
{
void move();
}

//car.java
public class car implements Vehicle
{
private String fuelType;
private int maxSpeed;

public void setFuelType(String FuelType)


{
this.fuelType = fuelType;
}

public void setMaxSpeed(int maxSpeed)


{
this.maxSpeed = masSpeed;
}

public void move()


{
System.out.println("fuelType: "+fuelType);
System.out.println("maxspeed: "+ maxSpeed);
System.out.println("car started happy journey");
}
};

//MotorBike.java
public class MotorBike implements Vehicle
{
private int maxSpeed;

public void setMaxSpeed(int maxSpeed)


{
this.maxSpeed = maxSpeed;
}

public void move()


{
System.out.println("maxSpeed: "+maxSpeed);
System.out.println("Fuel Type: petrol");
System.out.println("MotorBike started happy journey");

}
};

springconfig.xml

<beans>
<bean id = "id1" class = "Car" >
<property name = "fuelType">
<value>Diesel</value>
</property>
<property name = "maxSpeed" value = "100"/>
</bean>
<bean id = "id2" class "MotorBike">
<property name = "maxSpeed" value = "100"/>
</bean>
</beans>

//springconfig.xml

<beans>
<bean id = "id1" class = "Car" >
<property name = "u">
<ref bean = "id1"/>
</property>
</bean>
</beans>

In the above xml file, only classes are configured but not an interface.
In springframework, interfaces are not allowed to configure into spring config
file, only classes are allowed.

//client.java
import org.springframework.core.io.*;
import org.springframework.beans-factory.*;
import org.springframework.beans-factory.xml.*;

class Client
{
Resource res1 = new ClasspathResource("spconfig.xml");
BeanFactory bf1 = new XmlBeanFactory(res1);
// parent container
Resource res2 = new ClasspathResource("spconfig.xml");
BeanFactory bf2 = new XmlBeanFactory(res2,bf1);
// child container
Object o = bf2.getBean("id3");
//getting a traveller object from container
Journey jo = (Journey)o ;
jo.startJourney();

};

D:\SpringTest2> javac *.java


D:\SpringTest2> java Client
o/p ; journey started
fuel type: diesel
maxSpeed : 100
car started : happy journey.

In the spconfig.xml, if we change fuel type property of car to petrol and if we


run the client application then we will get the following output.
Journey started, fuel type, petrol, maxspeed =100
Car started happy journey.

 In spconfig.xml, change <ref> from id1 to id2 and if we run the client
application again then we will get the following o/p:
Journey started
Fuel type: petrol
maxSpeed: 80
MotorBike started happy journey.

In spconfig.xml, if we change id1 to id then springIOC container is injecting


MotorBike object into Traveller by replacing Car object. In this process the
programmer is not doing any change in the java code and not recompiling any
files, because of loose coupling between the objects, this runtime injection of
different objects into a class is possible.

In the above client application, we can add the following code to get the Car
class object throw child factory.
Object o1 = factory.getBean(“id1”);
Car c = (Car)o1;
c.move( ) ;

 If we run the above client application then we will get the following o/p.
Journey started
Fuel type: petrol
Maxspeed: 80
Car started.
Jdbc does not support: i) collections ii) Inheritance

 In the client application we can typecast the given bean object into either its
class type or its interface type.
 In the above client application we can directly typecast the objects into
Journey interface type using a single statement.

Journey j = (journey) factory.getBean(“id3”);

Dependency in the form of collections:


While creating a spring bean (pojo), the bean class can use any of the
following four types of collections as a dependency.
i) <set> Set (unordered, unique)
ii) <list> List (ordered, unique)
iii) <map> Map
iv) <properties> Properties
 Except the above four type 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
config (xml file), we need to use <set>, to inform the SpringIOC
container.
 In spring configuration file, we can use <value> and <ref> sub elements
of <set>
 While configuring <set> in the xml file, it doesn’t allow duplicate values,
because Set Collection is a unique collection.
 In spring framework, if one bean class is collaborating with another
bean class then SpringIOC container first creates collaboration bean
object and after that dependent bean object.

public class SampleBean


{
private Set data;

public setDate(Set data)


{
this.data = data;
}

public void m1()


{
---------------------
---------------------
}
};

spconfig.xml

<beans>
<bean id="id1" class = "SampleBean">
<property name = "data">
<set>
<value>100</value>
<value>sathya</value>
<value>1025</value>
<ref bean = "id2" />
</set>
</property>
</bean>
<bean id="id2" class = "restBean">
</beans>

In client application, whenever we call factory.getBean(“id1”) internally spring


container framework executes the following code.

TestBean tb = new TestBean();


Set s = new HashSet();
s.add(100); s.add(“sathya”);s.add(10.20);

SampleBean ob = new SampleBean();


ob.setData(s);

List Collection:
 If a springBean is depending on a collection of type list them in spring
config file, we need to configure <list>
 We can use <value> and <ref> as sub elements of <list>. The difference
between set and list collections are

Set List
1. Set is an unordered 1. List is an ordered collection.
collection.
2. Set doesn’t allow duplicate 2. List allows duplicate values.
values
3. Set doesn’t allow index based 3. List allows index based
accessing. accessing.
4. Set doesn’t support List 4. List supports ListIterator
Iterator.

Eg:
public class SampleBean
{
private List data;
public setData(List data)
{
this.data = data;
}
public void m1()
{
}

};

SPConfig.xml
<beans>
<bean id="id1" class = "SampleBean" >
<property name = "data">
<list>
<value> sathya </value>
<value>100</value>
<value>10.25</value>
<ref bean= "id2" />
<value>100 </value>
</list> </property> </bean>
<bean id="id2" class="TestBean"/>
</beans>
 In client application, whenever we call factory.getBean(“id1”) then
internally springcontainer framework executes the following code.
TestBean tb = new TestBean();
List l = new ArrayList();
l.add(“sathya”); l.add(100); l.add(10.25);l.add(tb);l.add(100);
SampleBean ob = new SampleBean();
ob.setData(l);
 If a Map collection contains 3 key,value pairs then internally it means 3
objects of MapEntry class.
Map Collection:
In a springbean, if we take collection type as Map then in spconfig file
we should configure the <Map>. In spconfig file, we need to use the sub
element of <Map> as <entry> in a Map collection one entry represents
(key, value)
We use sub element of <entry> as either <value> or <ref>
Eg:
public class SampleBean
{
private Map data;
public setData(Map data)
{
this.data = data;
}
public void m1()
{
}
};

SPConfig.xml
<beans>
<bean id="id1" class = "SampleBean" >
<property name = "data">
<map>
<entry key = "k1">
<value> sathya </value> </entry>
<entry key="10">
<value>100</value> </entry>
<entry key="k2">
<ref bean= "id2" /> </entry>
<value>100 </value>
</map> </property> </bean>
<bean id="id2" class="TestBean"/>
</beans>

Ex2:
The following example has storing by typed Map collection.
public class SampleBean
{
private Map<String, Float> data;
public setData(Map<String, Float> data)
{
this.data = data;
}
public void m1()
{
}
};

<beans>
<bean id="id1" class = "SampleBean" >
<property name = "data">
<map>
<entry key = "k1">
<value> 10.20 </value> </entry>
<entry key="10">
<value>15.20</value> </entry>
<entry key="k2">
<ref bean= "id2" /> </entry>
<value>18.92 </value>
</map> </property> </bean>
<bean id="id2" class="TestBean"/>
</beans>

Collection Key Value


Hashtable String Object
Properties String String
Map Object Object
Map:
“k1” – 100 //entity1 (one key,value is know as one entity)
“k2” – 10.25 //entity2
“k3” – Durga //entity3

a) What is the difference between an inner class and a nested class?


Ans: A non-static inner class is called inner class and a static inner class is
called nested class.

//inner class
class A
{
class B //inner class
{
----------
----------
};
};

//nested class
class A
{
static class B // nested class
{
------------
------------
};
};

Q) What is Map.Entity in java?


Ans: MapEntity is a class. Here Map is an Interface and Entity is a static class of
Map interface.
A Map stores data in the form of (key, values and we call each pair as one entity).
In the statement Map Entity, the meaning is we can enter static classes inside an
interface. We call those classes as nested classes.

public interface Map


{
-----------------
Static class Entity
{
----------- // getKey();
-----------// getValue();
}
}

In spring: upto jdk 1.4 key=String, value= any object


From jdk 1.5 key=any object, value= any object

Properties Collection: Properties collection also stores data in form of (key,


value). But both key and value are considered Strings.
 If we take properties collection in the spring bean then in the spring
configuration file, we need to use <propo>.
 The sub element of <propo> is <prop> and <prop> doesn’t have any sub
element.

public class SampleBean


{
private Properties data;

public void setData(Properties data)


{
this.data = data;
}
------------
------------
};

<beans>
<bean id="id1" class = "SampleBean" >
<property name = "data">
<propo>
<prop key = "k1">Durga</prop>
<prop key = "k2">100</prop>
</propo>
</property>
</beans>
 The following app is for injecting collection dependencies into a spring bean
E:\ -> Durga -> spconfig.xml
C:\ -> SpringTest3 ->SampleBean.java, client.java, *.class

//SampleBean.java
import java.util.*;
public class SampleBean
{
private Map<String, Integer> Students;
private List data;

public void setStudents(Map<String,Integer>Students)


{
this.Students = Students;
}

public void setData(List data)


{
this.data = data;
}

public void printMap()


{
Set s = Students.entrySet();
Iterator it = s.iterator();
while(it.hasNext())
{
Map.Entry me = (Map.Entry)it.next();
System.out.println(me.getKey()+" "+me.getValue());

}
}

pubic void printList()


{
Iterator it = data.iterator();
while(it.hasNext())
{
Object o = it.next();
System.out.println(o.toString());
}
}
};

//SPconfig.xml
<bean>
<bean id="id1" class = "SampleBean">
<property name = "Students">
<map>
<entry key = "Ram">
<value> 500 </value> </entry>
<entry key = "java">
<value> 999 </value> </entry>
</map> </property>
<property name = "data">
<list>
<value> Durga </value>
<value> 120 </value>
<value> 30.67 </value>
</list>
</property>
</bean>
</beans>

//Client.java
import org.springframework.core.io.*;
import org.springframework.beans.factory.*;
import org.springframework.beans.factory.xml.*;

public class client


{
public static void main()
{
Resource res = new FileSystemResource("E:/durga/spconfig.xml");
BeanFactory bf = new XmlBeanFactory(res);
Obect o = bf.getBean("id1");
SampleBean sb = (SampleBean)o;
sb.printMap();
sb.printList();
}
};
IMP points: In spring framework, for Resource interface, we have two
implementation classes, 1) Classpath Resource 2)FileSystemResource
 In ClassPathResource, the SpringFramwork verifies for the spring config xml
file in the local classpath, otherwise in the jar files added in the classpath.
 If the spring config file is not available in the classpath then spring framework
throws an Exception.
 While creating an object of ClassPathResource, we can’t pass path of the
springconfig file. It only accepts xml file name.

Resource res = new ClassPathResource(“E:\sathya\spconfig.xml”)


Resource res = new ClassPathResource(“SPConfig.xml”);
 In FileSystemResource, spring framework verifies for the spconfig file in the
given path. If not available then spring framework throws an exception.
 In FileSystemResource, xml file can be loaded from anywhere in system.
 The difference between ClassPathResource and FileSystemResource is, in
ClassPathResource xml file is loaded only from the classpath, but in
FileSystemResource it can be loaded from any place in the system.
 In the above client application we have used
FileSystemResource…………………………………….
 If we want to use ClassPathResource instead of FileSystemResource then the
following changes are required.
 In the client application, add the following statement
Resource res = new ClassPathResource(“SPConfig.xml”);
a) Create a jar file for the xml file
E:\durga\jar –cvf me.jar
b) Set me.jar into the classpath.
C:\springTest3>set classpath = %classpaht%;E:\durga\me.jar
c) Compile and run the client application
javac Client.java
java Client

Constructor injection:
 In this type of injection, spring framework or spring Container uses
constructor of the bean class for assigning the dependencies.
 In spconfig file, we need to inform the springIOC container about
constructor injection by using <constructor-arg>
 In the springbean class, if both constructor and setter injection applied for
the same property then constructor injection will be overridden by setter
injection.
For ex:
public class DemoBean
{
private String message;

public DemoBean(String message)


{
this.message = message;
}

public void setMessage(String message)


{
this.message = message;
}

public void show()


{
System.out.println(message); //hello
}
}

<beans>
<bean id="id1" class="DemoBean">
<constructor-arg>...constructor injection
<value>welcome </value>
</constructor-arg>
<property name="message">
<value>hello</value>
</property>
</bean>
</beans>

 In the client application, we call factory.getBean(“id1”) then ---nally spring


framework executes the following statements.
DemoBean ob = new DemoBean(“welcome”);
ob.setMessage(“hello”);
 First constructor injection executed and after that setter injection executed.
So welcome is overridden with hello.
 In constructor injection, if argument types are different them at time of
configuring at xml file, we can use type attribute.
<beans>
<bean id="id1" class="DemoBean">
<constructor-arg type="java.lang.String">
<value>10</value>
</constructor-arg>
<constructor-arg>
<value>100</value>
</constructor-arg>
</bean>
</beans>

public class DemoBean


{
private int id;
private String sname;
public DemoBean(int id, String sname)
{
this.id = id;
this.name = sname;
}
------------
------------
}
};

 According to the above xml, DemoBean obj is created with 100 as id and 10 as
sname.
public class DemoBean
{
public String uname,pwd;
public DemoBean(String uname, String pwd)
{
this.uname = uname;
this.pwd = pwd;
}
------------
------------
}
};

<beans>
<bean id="id1" class="DemoBean">
<constructor-arg index="1" value="sathya"/>
<constructor-arg index="0" value="ten" />
</bean>
</beans>

 According to the above xml DemoBean object is created with ten as username
and sathya as password.

public class DemoBean


{
private sampleBean sb;
public DemoBean(SampleBean sb)
{
this.sb = sb;
}
------------
------------
}
};

<beans>
<bean id="id1" class="DemoBean">
<constructor-arg ref = "id2"/>
</bean>
<bean id = "id2" class="sampleBean"/>
</beans>

 In the above xml file ref is used as an attribute, it is equal to ref bean. It is not
equal to ref local and ref parent.

Circular Dependency:
Q. what is circular dependency?
Ans: If A and B are two classes and if A depends on B and B depends on A then
we will get circular dependency.
 Whenever circular dependency is occurred then we can’t solve this problem
with the help of constructor injection in this case instead of constructor
injection we need to use setter injection.
For ex:
class A
{
B b;
A(B b)
{
this.b = b;
}
};

class B
{
A a;
B(A a)
{
this.a=a;
}
};

<beans>
<bean id="id1" class="A">
<constructor-arg ref = "id2"/>
</bean>
<bean id = "id2" class="B">
<constructor-arg ref = "id1"/>
</bean>
</beans>

 In a client application, whenever we call factory.getBean(“id1”), then springIOC


container is trying to execute class A object, but A needs B object, so the
container tries to create B class Object. But B class needs A object. So A and
B objects are not created and spring container throws bean currently in
creation Exception.
 In order to solve the circular dependency problem b/w
classes………………………………. We need to change/ replace constructor
injection with setter injection at class A.
Ex:
class A
{
B b;
public void setB(B b)
{
this.b = b;
}
};

//spconfig.xml
<beans>
<bean id="id1" class="A">
<property name="b" ref = "id2"/>
</bean>
<bean id = "id2" class="B">
<constructor-arg ref = "id1"/>
</bean>
</beans>

 In the client application, whenever we call factory.getBean(“id1”) internally the


following steps are executed.
Step1: spring container creates a mock (empty) object of class A using default
constructor.
Step2: Spring container creates class B object by passing the mock obj of class
A into its constructor.
Step3: Spring container injects class B obj into class A by calling setter
method.
Step4: finally class A obj is given back to the client application.

Q. What are the differences between constructor, setter injections?


Setter injection Constructor injection
1. Setter injection makes bean 1. Constructor injection makes
objects mutable. bean object as immutable.
2. In setter injection, partial 2. In constructor injection part
injection of dependencies is injection of dependency is not
possible. possible
3. Setter injection can solve 3. Constructor injection doesn’t
circular dependency problem. solve circular dependency
4. Setter injection overrides the problem.
constructor injected value. 4. Constructor injection doesn’t
override setter injected value.

Note: If a class contains more number of properties. Constructor injection is


recommended to use (because we can reduce length of the code of class).

If a bean class contains multiple constructors then we need to configure the


bean class multiple times with different id’s into spring config file.

For eg:

class A
{
private int id;
private String sname;

A(int id, String sname)


{
this.id = id;
this.sname = sname;
}

A(int a, int b, int c)


{
this.a = a;
this.b = b;
this.c = c;
}

A(String sname, int id)


{
this.sname = sname;
this.id = id;
}
};
//spconfig.xml
<beans>
<bean id="id1" class="A">
<constructor-arg value="10"/>
<constructor-arg type="java.lang.String" value="100"/>
</bean>
<bean id="id2" class="A">
<constructor-arg value = "10">
<constructor-arg value = "20">
<constructor-arg value = "30">
</bean>
</beans>

 In the above example, whenever we call factory.getBean(“id1”) from the client


application then spring framework creates an object of class A by calling first
constructor.
Bean autowriting:-
Writing a bean means configuring a bean along with it’s dependency into an xml
like.
By default were the bean properties into an xml file
If auto writing is enabled then springfw will take care about injecting the
dependencies and program is no need to configure into an .xml file explicitly
Bean auto writing is only supported, if the dependencies are in the form of
objects.
To enable auto writing , we should add autowrite attribute to the <bean>
1)dynamic 2) bytype 3) constructor 4) autodetect 5) name

1) Byname:- in this case, springfw attempts to bindout a bean in the confi


file, whose id is matching with the property name to be wired.
2) if a bean found, with the id as property name then that class obj with be
injected into that property by calling setter injection.
3) If no id found that property remains unwide.

Example:- public class exampleBean1


{
Privat ExampleBean2
Public void setEb2(ExampleBeaan2 eb2)
{
This.eb2=eb2;
}
}

Spconfig.xml:-
<beans>
<bean id=”id1 class=”ExampleBean1”
Autowrite=”byname”>
</bean>
<bean id=”id2” class=”ExampleBean2”/>
</beans>

2)Bytype:in the case the springfw attempts to bind out the class in xml file
whose name Is matching with the property type to be wired (or) not.
if found then injection that class obj by calling setter injection
if no class found in the xml with the same name then that property remains
unwired.
If a class is found in xml for more than once then springfw throws unsatisfied
dependency injection exception.

Example:- public class ExampleBean1


{
Private ExampleBean2 eb2;
Public void setEb2(ExampleBean2 eb2)
{
This.eb2=eb2;
}
}
Spconfig.xml:-
<beans>
<bean id=”id1” class =”ExampleBean1”
Autowire=”bytype”/>
<bean id=”id2” class=”ExampleBean2”
</beans>

3)constructor:- This autowrite type is equal to bytype but here constructor


injection will be encountered.

Example:- public class Ex1


{
private Ex2 eb2
public Ex1(Ex2 eb2)
{
This.eb2=eb2;
}
}
<beans>
<bean id=”id1” class=”Ex1” autowire=”constructor”/>
<bean id=”id2 class=”Ex2”/>
</beans>
4)autodetect:-the type of autowiring first work like a constructor and if not then
works like bytype.
Validating the dependency:- in springfw, either in explicit wiring or in autowiring
if all properties are not configured in xml, but still spring continer creates a n
object of the bean class.
By default springcontainer doesn’t verify whether call properties are set in xml
(or) not.
If we enable the dependency validation then spring container verifies whether all
dependencies are set (or) not if not then container doesn’t create an obj and
throws an exception.
To enable dependency validation, we need to add dependency-check attribute for
the <bean>
The different values of dependency-check attributes are
1) No(default) 2) simple 3) objects 4) all

Simple:-in this case spring container verifies for primitives and collections are set
(or) not. If not set then exception will be thrown.

Object:-in this case, spring container verifies whether objects are set (or) not, if
not the container throws an exception.

All:-in this case the container verifies for both primitives collections and objects.

Example:- public class TestBean


{
Private int a;
Private int b;
Public void seta(int a)
{
This.a=a;
}
Public void setB(int b)
{
This=b;
}
}
<beans>
<bean id=”id1” class =”TestBean”
Dependency-check=”simple”>
<property name=”a” value=”10”/>
</beans>
</beans>
In the above example property b is not in the xml. So simple dependency
validation is failed. Then an excepting will be occurred.

Example:-public class TestBean


{
Private DemoBeandb;
Private int a;
Private int b;
Public void seta(int a)
{
This.a=a;
}
Public void setB(int b)
{
This.b=b;
}
Public void setDb(DemoBeandb)
{
This.db=db
}
}
<bean id=”id1” class=”Testbean”
Dependency-check=”objects”>
<property name=”a” value=”10”/>
</bean>

In the above example, because dependency-check=”objects” it only verifies for


object dependency and spring container throws an exception, because the object
is not injected.
The following spring application is for validating the dependencies for objects
This spring application uses second spring IOC container called application
context.

//car.java
Public class car
{
Private void setW(wheel w)
[
This.w=w;
}
Public void display()
{
Sop(“done”);
}
}

springTest3
car.java
wheel.java
client.java
*.classes
Spconfig.xml

.wheel.java
Public class wheel
{
---
};

It is not a empty class because in java every class (empty)


Contain public, default constructor it is nothing but a method
In java it is not possible to write empty class.

Spconfig.xml
<beans>
<bean id=”id1” class=”car” dependency-check =”objects”/>
<bean id=”id2” class=”wheel”/>
</beans>

//client.java:-
Import org.springframework.context.*;
Import org.springframework.support.*;
Class client
{
Public svm()
ApplicationContext ctx=new classpathXmlApplicationContext(“spconfig.xml”)
Object o=ctx.getBean(id1”);
Car c=(Car)o;
c.display ( );
}
}

In the above client application, we have used the second spring IOC container
called ApplicationContext.
In springfw, we have two IOC container.
1)BeanFactory
2) Applicationcontext

BeanFactory is called as basic IOC container and Application context is called an


advanced IOC container

Applicationl context interface:-This spring IOC container is given in


org.springframework.context.* package and it’s implementation classes are given
in org.springframework.context.support package.
Applicationcontext interface has three implementation classes.
In Frameworks, interface and their implementation classes, both are given by
framework only.

BeanFactory-(i)
Applicationcontext(i)

ClasspathXmlApplicationContext(c) XmlwebApplicationContex(c)

FilesystemXmlApplicationContex(c)

ClasspathXmlApplicationContext loads(Reads) the spcofig file either from the


local classpath(or) from a jar file which is added in the classpath.
Filesystem XmlApplicationcontext always loads from filesystem of the system.
XmlWebApplication.Context is used, when spring beans are a part of web
application
ApplicationContext ctx=new
ClassPathXmlApplicationContext(“E:/sathya/spconfig.xml”);
The xml file path is not allowed.
ApplicationContext ctx= new
FileSystemXmlApplicationContext(“E:/sathya/spconfig.xml”)
ApplicationContext ctx= new
FileSystemXmlApplicationContext(“spconfig.xml”);allowed
In this case, the xml file is secured in the local folder

Bean initializing and destruction :-


While creating our bean class is spring, apart from injection we can also create
methods for performing initialization and decimalization (clean-up) code required
for the bean class.
In a springbean if we want to add some initialization code and cleanup code then
we need to implement our spring bean class from initializing and DisposableBean
interfaces.
If we implement the above two interfaces then in our spring bean class we have to
override the following methods.
1)after PropertieSet() from Initializing Bean interface
2) destroy() from DisPosableBean interface.

For example:-
Public class TestBean implements InitializingBean, DisposableBean
{
Public Void afterPropertiesSet()
{
//initialization logic
}
Public void destroy()
{
Deinitiaalization (clean-up)logic
}
}
It Is not a pojo class.
In the above bean class, whenever client request is given for getting the bean
object then internally the following steps are executed.
1) Object is created.
2) Properties are injected
3) After PropertiesSet() called.
4) Now obj is given to client application,
Before container is removing (destroying) the object, container first calls destroy ()
and then removes that obj from memory .
In the above example, the drawback is our class is not a POJO class . Because it
is implementing from predefined interface given by the framework.
So we can rewrite the above bean class by adding our own methods for initializing
and cleanup.

For example:- public class TestBean


{
Public void init()
{
//initialization code
}
Public void teardown()
{
//destruction code(cleanup)
}
}

While configuring the above into xml, we have to add init-method, destroy-
method attributes for the <bean>
<bean id=”id1” class=”TestBean” init-method=”init”
Destroy-method=”teardown”>
--
</bean>
In this case container will do the following, before giving the object to a client.
1) Object is created
2) Properties are injected.
3) Innit() will be called.
4) Object is given to client.
Whenever container is giving to remove the first it calls teardown() and after that
the object is removed.

BeanScops in springFw:- By default every springbean is singleton. It means even


though we call getBean() from client for multiple times but only one object is
created and it will be given for multiple times.
If we want a separate bean obj for each time whenever we call getBean() then we
need to change the beanscope. From singleton to prototype.
If we want to change the bean scope then we need scope attribute.
<bean id=”id1” class=”TestBean” singleton=”true/false”/>
<bean id=”id1” class=”clasname” scope=”prototype”/>spring2.x
In spring2.x, we have the following five scopes added.
For a bean
1) Singleton(default) 2) prototype 3) request 4) session 5) global session
application
Request.session and global session are used in springMVc application
development (web applications).

Bean instantiation:-
Spring framework instantiates/gets a spring bean object, by using the following
three ways.
1) By calling constructor.
2) By calling static factory method.
3) By calling an instance factory method.

1)By calling constructor:- whenever we call getBean(“id”) from the client


application then the springIOC container uses new operator and calls constructor
of the class and gets an objects of the bean class.
After getting the bean obj, it will apply injections and after that other
initializations and then returns that bean object to the client application.
If we change the bean scope to prototype then the IOC container gets/creates a
new object for each call to the getBean(“id”)

2)By calling static factory method:- by default, spring framework makes each
bean as singleton .But whenever the scope of a bean is changed to prototype then
the bean obj becomes non.singleton
If spring programmer doesn’t want to make a springbean as prototype bean then
the programmer has to explicitly make the bean class as singleton
To make a springbean class as a singleton, the following rules are need to be
followed.
1) Create a private static obj of the class, inside the class
2) Create a private constructor.
3) Crete a public static factory method.

For example:- public class SampleBean


{
Private static SampleBean sb=new SampleBean();
Private SampleBean()
{

}
Public static SampleBean getSampleBean()
{
return sb;
}
}

While constructing the above bean class into spring config file we need to inform
to the springIOC container that, call static factory method of the bean class to get
an obj of the bean class.
To inform the springIOC container, we should add an attribute called factory-
method to the <bean>
<bean id=”id1” class=”sampleBean”
*factory-method=”getSampleBean”

..
</bean>

Whenever getBean() is called from the client application then the IOC container
will get the bean object by using the following statement internally.
(SampleBean sb=SampleBeangetSampleBean();)
After getting the obj. the IOC container applies all injections and initialization
required and then finally returns that bean obj to the client application.

Note:- if we change scope of the bean from singleton to prototype then, still the
bean is a singleton bean only. It means that bean never out as prototype bean.

Question:-how to create synchronized singleton class in java?


If we add synchronized wayward for the static factory method then the class
becomes synchronized system class.

3)By calling an instance factory method:- in this approach springIOC container


calls the factory method defined in one class to get an obj 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 returns same class object but a factory method
must return an object
Public class SampleBean1
{
……
……
}
Public class SampleBean2
{
Public SampleBean1 getInstance()
{
SampleBean1 sb1=new SampleBean()
Return sb1;
}
}
<bean id=”id1” factory.bean=”id2” factory-method=”getInstance”/>
<bean id=’id2” class=”SampleBean2”/>

In the above xml, for the bean id1 we have removed class attributes and we have
added factory-bean.
In a client applicaton, whenever we call factory.getBean(“id1”),internally the
following staments are executed by the container.
SampleBean2 ob2=new SampleBean();
SampleBean ob1=ob2=getInstance();

Question:- how to make a java class as immutable?


We can make a java class as immutable by following the below rules.
1) Instance variables of the class must be private and final.
2) Class must containe a public parameterized constructor.
3) Define getter methods for the variables and avoid setter methods.
For example:- public class Sample
{
Private final int x,y;
Public Sample(intx,inty)
{
This.x=x;
This.y=y;
}
Public int getx()
{
Returns x;
Public int gety()
{
Returns y;
}
}

Question:-can we assign value for private final variable using setter methods
(or) not.
Not possible.
For final instance variables of the class, initialization must be done through
constructor but not through setter.

For example:- public class DemoBean


{
Private final int m;
Public DemoBean (int m);
{
This.m=m;
}
}

Spconfig.xml
<bean id=”id1” class=”DemoBean”>
<constructor-arg value=”100”/>
</bean>

Bean life cycle:-


1) Doesn’t exist
2) Instantiation
3) Initialization
4) Service
5) Destroy
Doesn’t exist factory.getBean(“id1) Instantiation

1) Inject dependencies
2)Calls setBeanName()
3)Calls setBeanFactory()
4)Calls
afterpropertiesSet()
5)Calls custom intimated

Destory service initialization

1) Custom destroy method


2) Calls destroy()

A Bean object life cycle is a circular process, which means the life cycle starts at
“doesn’t exit” and finally ends at “doesn’t exit” only.

Whenever we call getBean() by passing id then the IOC container creates an


object of the bean class. It means the bean object is moved from doesn’t exist
stage into instantiation.

After a bean obj is created, the IOC container initializes the object through the
following verifications.

a) Container verifies whether dependencies are exist (or) not.if exist then it
injects the dependencies.
b) The container verifies whether the bean class is implemented from
BeanNameAware interface (or) not if yes then container calls
SetBeanName(), by passing id of that bean.
c) Container verifies whether bean class is implemented from
BeanFactoryAware interface (or) not . if yes then calls SetBeanFactory
method by passing the current container (this) object.
d) Container verifies whether bean class is implemented initializing bean
interface (or) not . if yes then calls afterPropertiesSet()
e) Container verifies any user defined init() is added (or) not if yes then
container calls that custom init()
f) By completing the above operations, the IOC container returns the
initialized bean object to the client application
g) In the client application service methods(Business method) of the bean are
called.
h) Whenever container is going to shutdown, it removes the bean object. It
means first container verifies whether any user defined destroy methods is
added (or) not. If yes then executes it. Implemented DisPosableBean
interface (or) not . if yes then container calls destroy() and finally makes the
bean obj as destroyed
i) When the bean obj is destroyed then again it goes back to “doesn’t exist”
stats.

Question:- what is the diff b/w the sprigIOC containers BeanFactory and
applicationContext?

BeanFactory is a Basic IOC container and Application context is an advanced


container which is extended from Bean Factory.

BeanFactory doesn’t support real time services added to a bean like mailing
messaging , i18n ….etc But Application context supports the services added to
the springbean.

For real time application ApplicationContext is soutable then BeanFactory.

You might also like