Sie sind auf Seite 1von 47

SPRING IOC:-

This is the basic core module of spring framework.


This module is used in any tier of java enterprise application.
This is an IOC implementation in java also known as IOC container
IOC(Inversion of control):-
It is an architectural pattern that describes to have an external entity wiring the system at
startup.
Dependency Injection(DI):-
It is a process of injecting the dependencies into an object.
The implementation of IOC is known as IOC container.
The spring core container is one such IOC implementations in java.
Spring core container is a part of spring framework.
!spring container will benefit our application simplifying in creating the object"connecting
them and managing the scope for the objects.
This avoids implementing multiple patterns such as Singleton and #actory.
Spring container supports working with $O%O&S'plain old java objects( .we don&t have to
implement or extend any predefined interface or class to our application classes to manage by
Spring.
Spring container supports injecting the dependencies in ) ways
*(Constructor injection
)(Setter method+property injection.
The objects managed by the spring core container are known as Spring beans.
Spring container spports ! styles of configring t"e spring #eans:-
*(Spring beans ,-. document.
)(/nnotations
0xample1 let us implement one application
++/ccounts2/OI.java
$ackage com.spring.examples3
$ublic interface /ccounts2/OI
4
$ublic double get5alance'int accno(3
$ublic void set5alance'int accno"double amt(3
6
++/ccounts2/O.java
$ackage com.spring.examples3
$ublic class /ccounts2/O implements /ccounts2/OI
4
$ublic void set5alance'int accno"double amt(
4
++here we need to implement %25C code for updating the balance into the database
++dummy code
System.out.println'7in set balance189accno(3
6
$ublic double get5alance'int accno(
4
++here we need to implement the %25C code for selecting the balance from the database.
System.out.println'7in get5alance189accno(3
:eturn ;<<<.<3
6
6
++2epositService.java
$ublic class 2epositService
4
$rivate /ccounts2/OI adao3
$ublic 2epositService'/ccounts2/OI a(
4
adao=a3
6
$ublic 5oolean deposit'int accno"double amt(
4
System.out.println'7in deposit189accno(3
double bal=adao.get5alance'accno(3
bal=bal9amt3
adao.set5alance'accno"bal(3
return 'true(3
6
6
++>ithdrawService.java
$ackage com.spring.examples3
$ublic class >ithdrawService
4
$rivate /ccounts2/OI adao3
$rivate Check-in5al cmb3
$ublic >ithdrawService'/ccounts2/OI a(
4
adao=a3
6
$ublic void setCheck-in5al'Check-in5al cmb(
4
this.cmb=cmb3
6
$ublic boolean withdraw'int accno"double amt(
4
System.out.println'7In withdraw189accno(3
double bal=adao.get5alance'accno(3
bal=balamt3
if'cmb.check5alance'accno"bal((
4
adao.set5alance'accno"bal(3
return true3
6
return false3
6
6
++Check-in5al.java1
$ackage com.spring.examples3
$ublic class Check-in5al
4
$rivate /ccounts2/OI adao3
$ublic Check-in5al'/ccounts2/OI a(
4
/dao=a3
6
$ublic 5oolean check5alance'int accno"double bal(
4
++?ere we need to implement the business logic to check the minimum balance.
++we may need to use the /ccounts2/O object for getting the account type and other re@uired
details from the database
++dummy logic
return 'bal!=<(3
6
6
++/ccountServices.java
$ackage com.spring.examples3
$ublic class /ccountServices3
4
$rivate 2epositService ds3
$rivate >ithdrawService ws3
$ublic /ccountServices'2epositService ds">ithdrawService ws(
4
this.ds=ds3
this.ws=ws3
6
$ublic 5oolean transfer/mount'int srcaccno"int destaccno"double amt(
4
System.out.println'7In transfer /mount8(3
if'ws.withdraw'srcaccno"amt((
4
ds.deposit'destaccno"amt(3
return true3
6
return false3
6++transfer/mount
6
Configring t"e syste$ to t"e spring core container:-
we can write the Spring beans ,-. document to configure the objects to the container.
we don&t have any predefined name for this file to create"we can save this file with any
suitable name.
%&'$y#eans()$l
Abeans xmlns1xsi=http1++www.wB.org+)<<*+,-.Schemainstance
xsi1Schema.ocation=http1++www.springframework.org+schema+beans
7http1++www.springframework.org+schema+beans+springbeansB.*.xsd
,mlns=http1++www.springframework.org+schema+beans!
ACDIn this case we are working with the latest version of spring i.e B.*"in case of working with
).< or B.< just replace B.* with the respective version !
ACDdeclare the spring bean !
Abean id=8adao8 class=8com.spring.examples./counts2/O8+!
ACDdeclaring another bean !
Abean id=8ds8 class=8com.spring.examples.2epositService8!
Aconstructorarg ref=8adao8 +!
A+bean!
Abean id=8as8 class=8com.spring.examples./ccountServices8!
Aconstructorarg ref=8ds8 +!
Aconstructorarg ref=8ws8 +!
A+bean!
Abean id=8cmb8 class=8com.spring.examples.Check-in5al8!
Aconstructorarg ref=8adao8 +!
A+bean!
Abean id=8ws8 class=8com.spring.examples.>ithdrawService8 !
Aconstructorarg ref=8adao8 +!
Aproperty name=8check-in5al8 ref=8cmb8 +!
A+bean!
A+beans!
%ust now we have created the spring beans xml document for the system"we now want to start
the container and access the objects created by the container.
Starting t"e spring core container:-
This is a simple process where we just need to create an object of
5ean#actory+/pplicationContext.
5ean#actory object will represent the spring container initialiEed.
Initaili*ing t"e spring core container+-
InitailiEing the spring core container is simple process of creating the 5ean#actory
object+/pplicationContext object.
org.springframework.beans.factory.xml.,ml5ean#actory is the built in implementation for
5ean#actory interface.
The ,ml5ean#actory takes the spring beans xml document as an input for initialiEing the
container.
,$l-ean.actory(Resorce):-
This constructor of ,ml5ean#actory can be used to create the object.
The constructor here takes :esource object as an argument" which can be
*(#ileSystem:esource
)(Class$ath:esource
B(Frl:esource
/).ileSyste$Resorce :- This object gets the document from the current file system"where we
can specify the absolutre path or relative path for locating the file.
The following constructor can be used to create #ileSystem:esource object1
#ileSystem:esource'String path(1
0g1
#ileSystem:esource r=new #ileSystem:esource'7mybeans.xml8(3
++This creates a #ileSystem:esource object locating the mybeans.xml file in current directory
++In case if the file is in a different directory then we need to specify the respective path.
,ml5ean#actory beans=new ,ml5ean#actory'r(3
++This will create the ,ml5ean#actory object for starting the spring core container.
the ,ml5ean#actory object supports the following methods for getting the bean object from
the container.
a(Object get5ean'String id(3
b(AT! get5ean'String id"class C(3
The second method is new in spring B.< ./nd in this case generics are used so that we don&t
re@uired to do the type casting.
++/ccountServicesTestCase.java
$ackage com.spring.examples3
Import org.springframework.core.io.#ileSystem:esource3
Import org.springframework.beans.factory.xml.,ml5ean#actory3
$ublic class /ccountServicesTestCase
4
$ublic static void main'String argsGH(
4
#ileSystem:esource r=new #ileSystem:esource'7mybeans.xml8(3
,ml5ean#actory beans=new ,ml5ean#actoryI3
/ccountServices as='/ccountServices(beans.get5ean'7as8(3
5oolean flag=as.transfer/mount'*<*"*<)"2ouble.parse2ouble'argsG<H((3
System.out.println'7Transfer amount result 189flag(3
6++main
6++class
Compiling and running the example1
To compile and run this program we need
*(%2J and
)(spring libraries
we can download the spring libraries from
*(www.springframework.org+
)(www.springsource.com sites
the current version we find for download.
we just get to download the Eip file from the above mentioned sites and extract it.
set the following jar files into the classpath.
a(org.springframework.asmB.*.*.:0.0/S0.jar
b(org.springframework.beansB.*.*.:0.0/S0.jar
c(org.springframeworkcoreB.*.*.:0.0/S0.jar
d(org.springframework.org.apache.commons.logging*.*.*.:0.0/S0.jar
#or all jar files set classpath in a file and name it as classpath.bat
when the /ccountServicesTestCase is executing"we know that execution starts with main'(
>hen the ,ml5ean#actory object is created i.e beans=new ,ml5ean#actory'r(3
This starts the spring core container./t this point container doesn&t create any object declared in
the xml document.
Once this object is created successfully we can use it to get the beans from the container.
/t this point of time the container re@uires to create the /ccountServices object and for which
it creates the dependencies.
/fter getting the /ccountServices object then we can invoke any of the methods present in the
object as per our re@uirement.
0nderstanding t"e spring #eans ,12 doc$ent:-
This document is used for declaring the objects that are to be created by the container.
%#eans3 tag:-
It is a root element for the spring beans xml document. Inside this tag we will be decalring all
the beans./nd this allows configuring of default values for few configurations.
%#ean3 tag:-
This tag is used to declare a spring bean.
we can repeat this tag one for each spring bean to declare.
each bean will be given with uni@ue identity"for this we use 7id8 attribute.
4g:-
Abean id=8b*8 class=8-y5ean*8 +!
Abean id=8b)8 class=8-y5ean)8 +!
Note:-
*(8id8 should be uni@ue within the container.
)(It cannot start with number.
B(it cannot have whitespace and special characters'in simple it is similar to the rules that we have
variable names in java(
Spring supports specifying multiple identifiers using 7name8 attribute of Abean! tag as
follows
Abean name=8b** b)) bBB 7 class=8-y5ean*8 +!
we can access this bean by using b** or b)) or bBB
beans.get5ean'7b**8(3 or
beans.get5ean'7b))8(3 or
beans.get5ean'7bBB8(3
Note:- we can use both 7id8 and 7name8 attributes into a single bean.
The Abean! tag can be declared without 7id8 attribute and 7name8 attribute"in such case we
may want to get the bean object by the classname.Or this is done when we declare bean inside
another bean.
The container can instantiate an object using a constructor of a class.
we use 7class8 attribute to specify the name of the class that the container has to create an
object.
4)a$ple:-
Abean id=8b*8 class=8com.spring.-y5ean*8 +!9
#or this container internally creates an object using noargument constructor of
com.spring.-y5ean* class. >e can access this object by using 7id8 attribute value i.e 7b*8.
Spring supports creating an object using argumented constructor.
Constrctor injection:-
Injecting the dependencies using the constructor arguments is known as Constructor injection.
K(?ow to configure Constructor injection with springL
Fsing Aconstructorarg! tag we can configure the constructor injection for the bean in spring
beans xml document.
The Aconstructorarg! tag supports using any one of the following tags as a child tags1
*(Aref!
)(Avalue!
B(Anull!
M(Alist!
;(Aset!
N(Amap!
O(Aprops!
P(Abean!
Avalue!1 This tag is used for configuring the basic datatypes and any other String based value.
4g:-
$ublic class -y5ean
4
$ublic -y5ean'String s( 4 . . . . .6
6
Configration:-
Abean id=8b*8 class=8-y5ean8!
Aconstructorarg!
Avalue!?elloA+value!
A+constructorarg! A+bean!
0g*1
$ublic class -y5ean
4
$ublic -y5ean'int count( 4 . . . . .6
6
Configration:-
Abean id=8b*8 class=8-y5ean8!
Aconstructorarg!
Avalue!*<A+value!
A+constructorarg!
A+bean!
Container can identify the datatype of the argument and automatically convert the value to that
type.In case if the conversion fails it will throw 5eanInstantiation0xception.
The Avalue! tag allows the 7type8 attribute specifying the datatype of the value.In general this
would be re@uired when we have overloading example1
4g:-
$ublic class -y5ean
4
$ublic -y5ean'int count( 4 . . .. 6
$ublic -y5ean'double amt( 4 . . . 6
. . . .
6
Configration:-
Abean id=8b*8 class=8-y5ean8 !
Aconstructorarg!
Avalue type=8int8!*<A+value!
A+constructorarg!
A+bean!
This creates an object of -y5ean class using int argument constructor.
%ref3tag:-
This tag is used to configure the bean reference.
4g:-
$ublic class -y5ean* 4 . . . . .6
$ublic class -y5ean)
4
$ublic -y5ean)'-y5ean* b( 4 . . . .6
6
Configration:-
Abean id=8b*8 class=8-y5ean*8+!
Abean id=8b)8 class=8-y5ean)8!
Aconstructorarg!
Aref local=8b*8 +!
A+constructorarg!
A+bean!
the Aref! tag allows any one of the following attributes1
*(local
)(parent
B(bean
/)local:- This is used to refer the bean in this container itself'i.e this spring xml document(
It will not allow using the 7name8 of the bean to refer.
!)parent:- This is used to refer the bean in the parent container.
It can use 7id8 or 7ame8 of the bean.
5)#ean:- This is used to refer the bean in this or parent container with 7id8 or 7name8.
Note:- The Aconstructorarg! supports using any of the following attributes as shortcuts for the
Avalue! and Aref! tags.
- - vale:- This is the shortcut for Avalue! tag
Abean id=8b*8 class=8-y5ean8!
Aconnstrutorarg!
Avalue!?elloA+value!
A+constructorarg!
'or( e@uivalent
Aconstructorarg value=8?ello8 +!
A+bean!
In case of specifying type
Aconstructorarg value=8*<8 type=8int8 +!
--ref:- This attribute is a shortcut for Aref! tag inside the Aconstructorarg!
Aconstructorarg!
Aref local=8b*8+!
A+constructorarg!
'or(
Aconstructorarg ref=8b*8+!
Aconstructorarg ref=8b*8 +! is e@uivalent to
Aconstructorarg!
Aref bean=8b*8+!
A+constructorarg!
In case of specifying as a local or parent "we cannot use shortcut.
Note:-
Aconstructorarg!tag can have only one among the 7ref8 and 7value8 attributes.It can exist
even without these ) attributes.
If any one of the attributes are used"this tag should be empty i.e no child tags.
6"e %nll3 tag:-
This is used to configure the java null to set the value.
This is an empty tag and has no attributes.
4g:-
Abean id=8b*8 class=8-y5ean8!
Aconstructorarg! Anull +!A+constructorarg!
A+bean!
6"e %list3 tag:- This is used to set the value for java /rray or java.util..ist type.
4g:-
$ublic class -y5ean
4
$ublic -y5ean'String namesGH( 4 . . .. 6
6
Configration:-
Abean id=8b*8 class=8-y5ean8!
Aconstructorarg!
Alist!
Avalue!user*A+value!
Avalue!user)A+value!
Avalue!userBA+value!
A+list!
A+constructorarg!
A+bean!
This tag allows Eero or more child tags./ny of the following tags can be child for this tag.
Qalue+ref+null+list+set+map+props+bean
4):-
$ublic class -y5ean'.ist l( 4 . . . .6
6
Configration:-
Abean id=8b*8 class=8-y5ean8!
Alist!
Avalue!user*A+value!Avalue type=8java.lang.Integer8!*A+value!
Aref local=8b)8+!
Alist!
Avalue!val*A+value!
Avalue!val)A+value!
A+list!
A+list!
A+constructorarg!
A+bean!
%set3 tag:-
This tag is used to configure java.util.Set type of object.
.ike Alist!"this Aset! tag also allows multiple child tags.the only difference is when using
the Aset! tag container creates java.util.Set type of object.
$ublic class -y5ean
4
$ublic -y5ean'Set s( 4 . . .. 6
6
Configration:-
Abean id=8b*8 class=8-y5ean8!
Aconstructorarg!
Aset!
Avalue!user*A+value!
Avalue!user)A+value!
Avalue!userBA+value!
A+set!
A+constructorarg!
A+bean!
Amap! tag1
This tag is used to configure the java.util.-apo type of object.
The Amap! tag allows Eero or more Aentry! tags./nd each Aentry! tag allows ) childs
"first is Akey! and second child is any one of the following tags
value+ref+null+list+set+map+props+bean.
The Akey! tag allows any one of the above tags.
4g:-
$ublic class -y5ean
4
$ublic -y5ean'-ap m( 4 . . . .6
6
Configration:-
Abean id=8b*8 class=8-y5ean8!
Aconstructorarg!
Amap!
Aentry!
Akey! Avalue! usernameA+value!A+key!
Avalue!user*A+value!
A+entry!
Aentry!
Akey!Avalue!dataA+value!A+key!
Alist!
Avalue!val*A+value!
Avalue!val)A+value!
A+list!
A+entry!
A+map!
A+constructorarg!
A+bean!
%props3 tag:- This tag is used to configure the java.util.$roperties type of object.
the Aprops! tag allows multiple Aprop! tags as childs.
The Aprop! tag allows 7key8 attribute for configuring the key.
4)a$ple:-
$ublic class -y5ean
4
$ublic -y5ean'$roperties p( 4 . . . .6
6
Configration :-
Abean id =8b*8 class= 7-y5ean8!
Aconstructorarg!
Aprops!
Aprop key=8username8!userA+prop!
Aprop key=8password8!passwordA+prop!
A+props!
A+constructorarg!
A+bean!
%#ean3 tag:-
/part from the above discussed tags we can use Abean! tag directly inside the Aconstructor
arg! decalring the bean.This is alternative to Aref! tag.
4)a$ple:-
$ublic class -y5ean)
4
$ublic -y5ean)'-y5ean* b*( 4 . .. . 6
6
Configration:-
Abean id=8b)8 class=8-y5ean)8!
Aconstructorarg!
Abean class=8-y5ean*8+!
A+constructorarg!
A+bean!
Configring $ltiple arg$ents for t"e constrctor:-
In case of multiple arguments we need to repeat Aconstructorarg! tag multiple times.
4)a$ple:-
$ublic class -y5ean
4
$ublic -y5ean'String s*"String s)( 4 . . . .6
6
Configration:-
Abean id=8b*8 class=8-y5ean8!
Aconstructorarg value=8val*8 +!
Aconstructorarg value=8val)8+!
A+bean!
we can use 7index8 attribute of the Aconstructorarg! tag to specify the argument index.
Abean id=8b*8 class=8-y5ean8!
Aconstructorarg value=8abc8 index=8*8 +!
Aconstructorarg value=8xyE8 index=8<8+!
A+bean!
?ere first argument is 7xyE8 and second argument is 7abc8.
Setter $et"od(Property) injection:-
/part from Constructor injection spring also supports setter method'$roperty( injection.
Injecting the dependencies using the setter method arguments is known as setter
method'propert( injection.
6"e setter $et"od is of t"e follo7ing signatre:-
Synta):- public void SetAname!'Aone argument!(
Note:- The Aname! should have the first character in uppercase.
The following tag is used in the Abean! to configure the property injection.
Aproperty name=8 7 ! . . . . .A+property!
The 7name8 attribute takes name of the property'setter method("here when we are using the
name we should make the first character to lower case.
The Aproperty! tag allows any one of the following tags as a child
Avalue!"Aref!"Anull!"Alist!"Aset!"Amap!"Aprops!"Abean!
4)a$ple:-
$ublic class -y5ean
4
$ublic void set2efaultCount'int i( 4 . . . .6
$ublic void setFserRame'String s( 4 . . . .6
$ublic void set-y5ean)'-y5ean) b)( 4 . . . .6
6
Configration:-
Abean id=8b*8 class=8-y5ean8!
Aproperty name=8defaultCount8!
Avalue type=8int8!*<A+value!
A+property!
Aproperty name=8username8 value=8user*8+!
Aproperty name=8my5ean)8!
Aref local=8b)8 +!
A+property!
A+bean!
Note:- These are the same tags whih we have used with the Aconstructorarg! tag.
when a Aproperty! is used it is mandatory to give 7name8.
6"e container internally perfor$s t"e follo7ing:-
* :ead the name from the Aproperty! tag.
) Converts the first character to upper case.
B /dds 7set8 as a prefix.
M Invokes the method with the name prepared in stepB and with one argument.
4)a$ple:-
Abean id=8ds8 class=8org.apache.commons.dbcp.5asic2ataSource8!
Aproperty name=8driverClassRame8 value=8oracle.jdbc.driver.Oracle2river8 +!
Aproperty name=8url8 value=8jdbc1oracle1thin1Slocalhost1*;)*1,08 +!
Aproperty name=8user8 value=8system8 +!
Aproperty name=8password8 value=8manager8 +!
A+bean!
p-na$espace:-
pnamespace is the simplified option for configuring the property injection which is an
alternative to Aproperty! tag.
To use this option add the following attribute into the Abeans ! tag1
,mlns1p=8http1++www.springframework.org+schema+p&
To configure the property we use the following attribute in the Abean! with the following
format1
P:%property8na$e3
4)a$ple:-
$ublic class -y5ean
4
$ublic void set2efaultCount'int i( 4 . . . .6
$ublic void setFserRame'String s( 4 . . . .6
9
Configration:-
Abean id=8b*8 class=8-y5ean8 p1count=8*<8 p1username=8abc8 + !
In case if the property type is a reference like -ybean)" we need to use the attribute name in
the following format1
Synta):- p1ApropertyTname!ref
4)a$ple:-
$ublic class -y5ean
4
$ublic void set2efaultCount'int i( 4 . . . .6
$ublic void setFserRame'String s( 4 . . . .6
$ublic void set-y5ean)'-y5ean) b)( 4 . . . .6
6
Configration:-
Abean id=8b*8 class=8-y5ean8 p1defaultCount=8*<8 p1username=8user8 p1my5ean)
ref=8b)8 +!
4)a$ple for #asic datasorce:-
Abean id=8ds8 class=8org.apache.commons.dbcp.5asic2ataSource8!
Aproperty name=8driverClassRame8 value=8oracle.jdbc.driver.Oracle2river8 +!
Aproperty name=8url8 value=8jdbc1oracle1thin1Slocalhost1*;)*1,08 +!
Aproperty name=8user8 value=8system8 +!
Aproperty name=8password8 value=8manager8 +!
A+bean!
(or) sing p-na$espace t"e configration $ay loo: li:e as follo7s
Abean id=8ds8 class=8org.apche.commons.dbcp.5asic2ataSource8
p1driverClassRame=8oracle.jdbc.driver.Oracle2river8
p1url=8jdbc1oracle1thin1Slocalhost1*;)*1,08 p1user=8system8 p1password=8manager8 +!
$ublic class -y5ean 4
$ublic void setFserRames'.ist l( 4 . . . . .6
6
%til:na$espace3:-
This is used to configure the Collection objects like list"set"map"and properties.
6o se t"is option 7e need to do t"e follo7ing ! t"ings:-
/)add t"e follo7ing rl into t"e ;Sc"e$a2ocation< of %#eans3 tag:-
http1++www.springframework.org+schema +util http1++www.springframework.org+schema+spring
utilB.*.xsd8
!)=dd t"e follo7ing attri#te into %#eans3 tag:-
,mlns1util=http1++www.springframework.org+schema+util
6"e follo7ing > tags are introdced into t"is na$espace:-
*(util1list
)(util1set
B(util1map
M(util1props
%til:list3:-
This is used to declare the java.util..ist or array type object.
This supports one attribute ie 7id8"which is similar to the 7id8 attreibute of Abean! tag.
This allows Eero or ore child tags like
Avalue!+Aref!+Anull!+Alist!+Aset!+Amap!+Aprops!+Abean!
4)a$ple:-
$ublic class -y5ean 4
$ublic void setFserRames'.istAString! names( 4 . . .. 6
6
Configration:-
Abeans!
Autil1list id=8names*8!
Avalue!-r abcA+value!
Avalue!-r xyEA+value!
A+util1list!
Abean id=8b*8 class=8-y5ean8 p1usernamesref=8names*8+!
/s shown above the 7id8 attribute value ie 7names*8 is used as similar to the 7id8 attribute of
the Abean! tag.
%til:set3:-
This is simar to the util1list! except it creates java.util.Set object
%til:$ap3:- This is used to configure the java.util.-ap object.
.ike Amap! tag this also allows Eero or more Aentry! tags.
4)a$ple:-
Autil1map id=8data8!
Aentry!
Akey!Avalue!FserRameA+value!A+key!
Avalue!systemA+value!
A+entry!
A+util1map!
%til:props3:-
This is used to configure the java.util.$roperties object.
4):-
Autil1props id=8p*8!
Aprop key=8user8!systemA+prop!
Aprop key=8password8!tigerA+prop!
A+util1props!
Spring -eans initiali*ation and destrction:-
The container creates the spring beans and ijects the dependencies by invoking the set
methods.In some cases we find a re@uirement of initialiEations to perform. Spring supports to do
this re@uirement.
Initaili*ing -ean:-
Spring core /$I includes an interface IntialiEing5ean"this declares only one method1
$ublic void after$opertiesSet'( throws 0xception3
The spring bean class can implement this method for initialiEations.
This method is executed after creating the object and executing all configured setter methods.
In case if this method throws any exception the bean will not be created and the container
throws 5eanCreation0xception to the client
The problem with this option is InitialiEing5ean interface is in
org.springframework.beans.factory package and when using this the bean class will get
dependent on the spring /$I.
6o solve t"is pro#le$? spring "as anot"er option:-
0sing init-$et"od:-
the 7initmethod8 attribute of Abean! is used to specify the 7name8 of the method.The method
should be of the following signature1
$ublic void AmethodTname!'( Gthrows 0xceptionH
4)a$ple:-
$ublic class -y5ean
4
$ublic void init'( 4
++initialiEation logic
6
Configration:-
Abean id=8b*8 class=8-y5ean8 initmethod=8init8 +!
Note:- we can use both the options together also i.e bean class can implement InitailiEing5ean
and also configure the intimethod.In such case the after$ropertiesSet'( method will be executed
then the initmethod will be executed.
In many cases we find most of the beans in the container have the same initmethod"instead of
configuring the initmethod repeatedly into every Abean! tag we can have 7defaultinitmethod8
attribute in Abeans! tag.
4)a$ple:-
Abeans . . . .. . defaultinitmethod=8init8!
Abean id=8b*8 class=8-y5ean*8+!
Abean id=8b)8 class=8-y5ean)8 +!
Abean id=8bB8 class=8-y5eanB8+!
Abean id=8bM8 class=8-y5eanM8 initmethod=8start8+!
A+beans!
The defaultinitmethod can be overridden for a particular bean.
SpringB introduces a new option for configuring initialiEation method.
we can use S$ostConstruct annotation to configure the initialiEation method.
4)a$ple:-
Import javax.annotatioin.U3
$ublic class -y5ean
4
S$ostConstruct
$ublic void init'(
4
++initialiEation logic
6
6
Note:- To use the annotation support we need to create the /pplicationContext instead of
5ean#actory for creating the container.
.ike we have seen earlier with ) options together"we can also use S$ostConstruct along with
InitaialiEing5ean and initmethod options.
*(InitailiEing5ean
)(initmethod attribute
B(S$ostConstruct annotation.
Note:- To use S$ostConstruct annotation to work"we need to add the following into xml
document.
/)=dd t"e follo7ing rl<s into t"e ;Sc"e$2ocation<
"ttp:@@777(springfra$e7or:(org@sc"e$a@conte)t
"ttp:@@777(springfra$e7or:@sc"e$a@conte)t@spring-conte)t-5(/()sd
!)=dd t"e follo7ing attri#te into %#eans3
,$lns:conte)tA"ttp:@@777(springfra$e7or:(org@sc"e$a@conte)t
5)=dd t"e follo7ing tag:-
Acontext1annotationconfig +!
In the TestCase we need to use /pplicationContext instead of 5ean#actory
Class$ath,ml/pplicationContext beans=new
Class$ath,ml/pplicationContext'7mybeans.xml8(3
#or this we have to import org.springframework.contaxt.supprt.U3
Destrction:-
.ike initialiEation"for destruction also spring supports B options '* is new in spring B.<( 1
*(using 2isposable5ean interface
)(using destroymethod attribute
B(using S$re2estroy annotation
/)Disposa#le-ean interface:-
the org.springframewrok.beans.factory.2isposable5ean interface declares only one method.
$ublic void destroy'(3
P#lic void destroy() :- this method is invoked by the container at the time of destroying the
bean.
4)a$ple:-
$ublic class -y5ean implements 2isposable5ean
4
$ublic void destroy'( 4
++here we implement finaliEation logic
6
6
The problem with this approach is the bean is getting dependent on the spring /$I.
6"e destroy-$et"od:-
Similar to initmethod"we can use destroymethod for configuring the destroy method.This is
useful in making the bean independent of Spring /$I.
4)a$ple:-
$ublic class -y5ean
4
$ublic void close'(
4
++implement finaliEation logic
6
6
Configration:-
Abean id=8b*8 class=8-y5ean8 destroymethod=8close8 +!
5)BPreDestroy annotation:-
This is new in springB.<
This is an alternate option for implementing the finaliEations for the bean.
4)a$ple:-
Import javax.annotation.U3
$ublic class -y5ean
4
S$re2estroy
$ublic void close'(
4
++implement finaliEation logic
6
6
Spring #eans scopes:-
Spring).< introduces support for multiple scopes.
The following ; scopes are builtin available with spring.
/)singleton:- This is the default scope for the beans.This scope configure the beans to create
only one instance for the spring bean. This is created at the time of starting the container or
re@uesting for the bean first time.
Note:- If we use 5ean#actory for starting the container"it will initialiEe the singleton beans at the
time of when we re@uest for the bean first time.
If we use /pplicationContext for starting the container"it will initaialiEe the singleton beans at
the time of starting the container.
we can use 7laEyinit8 attribute for configuring the bean not to initialiEe at the time of starting
the container.
Prototype:- If we configure this scope for a bean"container creates one new instance for every
re@uest for the bean.
ReCest:- >ith this scope container creates one instance in a Servlet+$ortal re@uest.
Session:- with this scope container creates one instance in ?ttpSession.
glo#alSession:- This will have only one instance per global session in a portal system.
Note:- The last B scopes are applicable to use in the web environment i.e Servlet and $ortal.
6"read:-
This is new in spring B.In this"one object is created for each thread.
Note:- 7the 7scope8 attribute of Abean! tag is used to configure the re@uired scope for the bean.
4g:- Abean id=8b*8 class=8-y5ean*8 scope=8singleton8 +!
Abean id=8b)8 class=8-y5ean)8 scope=8prototype8 +!
Note:- scope names are casesensitive.
1et"od Injection:-
The spring container supports injecting the method for pulling the beans into our bean.
In case of singleton bean depending on prototype bean we find problem in using the
constructor or setter method injection by the spring container.
In this case we want to get the prototype bean from the container every time it is re@uired so that
we can have a separate instance working for each client.
In support of this re@uirement spring container includes the method Injection.
we use the following tag for configuring the method injection.
Alookupmethod name=8 7 bean=8 7 +!
The 7name8 attribute takes the name of the method to implement.The 7bean8 attribute takes
the 7id8 of the bean that has to be returned.The method signature should be as shown blow1
$ublic GabstractHAnonvoid! AmethodTname!'(3
4)a$ple:-
$ublic abstract class -y5ean*
4 public abstract -y5ean) get-y5ean)'(3
$ublic void my-ethod'(
4
-y5ean) b)=get-y5ean)'(3
++use b)
6
6
Configration:-
Abean id=8b)8 class=8-y5ean)8 scope=8prototype8+!
Abean id=8b*8 class=8-y5ean*8 !
Alookupmethod name=8get-y5ean)8 bean=8b)8+!
A+bean!
with this configuration container will create subclass for -y5ean* and implementing
get-y5ean)'(.This method is implemented to get the bean 7b)8 from the container and
return./nd the container creates an object for the subclass implemented by it.
-y5ean* b*='. . . (beans.get5ean'7b*8(3
Instantiating t"e #ean:-
/part from using the Constructor"container supports creating the object usig the static and
nonstatic factory methods.
0sing static factory $et"ods for instantiation:-
In this case we will use the following attributes in the Abeana! tag1
class:- specifie the name of the class'with the package name(
factory-$et"od:- specifies the name of the method to create the objects.
4)a$ple:-
$ublic class -ybean
4
$rivate -ybean'( 4 . . . 6
$ublic static -ybean getInstance'(
4
:eturn new -ybean'(3
6
6
Configration:-
Abean id=8b*8 class=8-ybean8 factorymethod=8getInstance8+!
spring supports arguments into the factorymethod"to configure the arguments we use the same
Aconstructorarg! tags.
4)a$ple:-
Abean id=8con8 class=8java.s@l.2river-anager8 factorymethod=8getConnection8!
Aconstructorarg value=8jdbc1odbc1mydsn8+!
Aconstructorarg value=8system8+!
Aconstructorarg value=8tiger8 +!
A+bean!
0sing non-static factory $et"ods:-
Spring supports even using nonstatic methods for creating the objects.
!we use the following attributes to configure this1
factory-#ean:- specifies the 7id8 of the bean whose method should be invoked.
factory-$et"od:- specifies the name of the method.
4)a$ple:-
$ublic class -ybean* 4 . . .. 6
$ublic class -ybean)4
$ublic -ybean* get-ybean*'( 4 . . .. .6
6
Configration:-
Abean id=8b)8 class 7-ybean)8 +!
Abean id=8b*8 factorybean=8b*8 factorymethod=8get-ybean*8 +!
One $ore e)a$ple:-
Abean id=8con8 class=8java.s@l.2river-anager8 factorymethod=8getConnection8!
. .. . .A+bean!
Abean id=8st8 factorybean=8con8 factorymethod=8createStatement8+!
That is spring supports configuring the bean using
constructors 'or(
static factory methods'or(
nonstatic factory methods for instantiation.

Das könnte Ihnen auch gefallen