Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

260
PART-1 Spring-IOC Spring-DAO http://javabynataraj.blogspot.com

description

Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Transcript of Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Page 1: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

PART-1

Spring-IOC

Spring-DAO

http://javabynataraj.blogspot.com

Page 2: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- ---- . - -. -. . . . -

S~r ing - IOC Bv Mr. SomaseitharReddv[Certified Professions:

Q) Where actually java is used? 4 Java is used to develop the enterprise applications. 4 Enterprise means business organization 4 Business organization provides services

Q) What is Enterprise Application? 4 Computerizing business applications

Architecture of Enterprise Ap~lication:

Client

Layer

Persistent

Layer

- Presentation

Layer

DATA BASE

-

Client Laver: > It is browser software.

-

&

Presentatation Laver: Roles: 9 Receiving user request from client tier (calling request) 9 Capturing the user provided data

Business

Layer

9 Validating the user input I

9 Calls the business method to get business < ,

9 Keep the processed data in memory. /

9 Forwarding the control t o output jsp i.

Note: should not write business logic in the presentation tier I Business Laver:

9 Receiving request from presentation tier 9 Contacting the persistent tier to get the database data 9 Implementing the business logic 9 Return the control to presentation tlier

Persistent Laver: I

9 Receiving the request from business tier 9 Contacting database to get the database data t

9 Return the accessed data to business tier

Data Laver: 9 It is a database.

Q) What are the different logics available in Enterprise Application?

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company

-- ~ -

Page 1 http://javabynataraj.blogspot.com

Page 3: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- - - - . - - -. . - - -- -

Spring-IOC By MI.. Sor.~aseltharReddy[Certified Professional)

Presentation Logic: This logic generally we w ~ l l write in JSP. Application/Controlling Logic: Generally we write this logic in controller. Bussiness Logic: Programmatical implementation of business rules is nothing but bussiness rules. DataAccess Logic: The logic which will we write to contact the DB.

Q) What are the Sun Microsystems technologies and frameworks in enterprise application development?

Presentation tier Servlets jsp's

Q) What are the non-Sun Microsystems technologies and frameworks in enterprise application development?

Business tier EJB2 session beans EJB3 session beans MDB(Message Driven Beans)

Persistent tier JDBC JPA(java persistent API)

Freemarker Spring Web MVC

Presentation tier Struts Velocity

I Persistent tier / Hibernate

Business tier Spring Aop Spring JEE Ibatis

Toplin k JDO Spring DAO Spring ORM

3 So spring is used to develop any layer of the Enterprise Application.

Note: 6 Spring is not a technology from sun micro system like JDBC, EJB, JSP, set-vlets ... etc 6 Spring is neither J2SE nor j2EE but it uses both

Q) What is spring actually? 6 It is a open source frame work 6 Spring is a light-weight framework e Industry treats spring as framework of framework.

Note: spring is very much successful in the industry in business tier development as an alternate to EJB2. Later on it is used in all layers of the application because of its light weightness.

Q) What is Framework? + It is a reusable semi-finished application that can be customized according to our business

requirement

Q) What is light-weight in context of spring? It is light-weight in terms of

1. Size of container 2. Processing over heads involved in giving the enterprise services 3. Business class dependency & amount of coupling with the framework

Q) What was the main objective of spring invention? 6 Simplification of j2ee application by reducing the complexity involved in enterprise application

development.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 certified Company

~ .

Page 2 http://javabynataraj.blogspot.com

Page 4: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

r - -. -. - - -

Spring-IOC -. - By Mr. SomasekharReddy(Certified Professional:-' ' i

Sprins Architecture

Spring JDBC Hibernate Transaction J PA JMX

' Spring AOP P EJ B'S

WEB MVC Spring web MVC Struts Web work JSF

Core

The IOC container

1) Core module: 6 The core module of spring framework is spring container. Spring beans are managed by spring r

container. G This module concentrates on major principles of IOC (Inversion Of Control) -

G We call IOC as heart of spring applications 6 IOC is a container used for holding spring beans

2) BAO module: 6 It is meant for building persistence tier (data access layer) 6 I n this framework i t provides :IDBC abstraction

3) ORM: G Spring provides an integration support with most of the ORM tools

I.

Ex: Hibernate, top Link, JPA, Ibatis ... etc i

4) JEE module: 6 This module provides the SUN enterprise services to the spring bean 4 I n this module spring has the support for integrating with EJB1s, RMI, JAVA Mail,

Transactions(JTA,JTS) ... etc

5) web MVC module: 4 This module is used to develop presentation tier of an Enterprise Application. + Spring has an implementation for the MVC design pattern we call it as spring MVC module 4 Spring also provides an integration with any MVC implementations like struts,JSF ... etc

6) AOP module: 6 To solve the cross cutting concern problems, spring using Aspect Oriented Programming(A0P) - 4 To provide declarative enterprise services (logging, security, transaction management ... etc) AOP is\

used. 4 Using AOP we can integrate other AOP framework also.

Ex: aspect]

Design pattern: solutions for repeated problems . Ex: SingleTon, Factory, MVC, business delegates, service locator..etc

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- An IS0 9001 : 2000 Certified Company - - -- - - - . -. -- - - - . -

Page 3 http://javabynataraj.blogspot.com

Page 5: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

$3 zrc !5J- (ciefault packagc:~

fyj I- Cotit iection.ja~a @A C o f i 1 i ~ c t i u 1 i U t i I 1 ~ ~ 1 ~ 2 O l . j a ~ . ~ a

& Conn~c t10nUt t l t r~ tC IO2. ja~~.~a ""

i,tj Con11ect1crnUtiIiz~1FJI:13.~a~,ca

Dj C~onncctionUt1Iizcro04.java

i$J ConnectionUti l i r~~OOS.java

j2 Conncc t ionUt1 I1z~ l t?~6 , ja~~a

IB Conn tctic-nLltilirer007.java

!& hRjrlT:ontainer.~a~.(a U-

Fdy5qICon nectionProvidcr.java i$J Orac l~Cc t~nrc t io t iP ru~~ ider , java

r n y p r o p ~ & ~ ~ s . p r ~ p ~ ~ t i e s JRE 55yztcns Library I; : " i :'i]

ConnectionUtilizer00l.iava 1. public class ConnectionUtilizerOOl {

2. public static void main(String[] args) {

3 . System. out .println ("this is Oracle Connection") ; 4. 1 5 . 1

d I n the above Utilizer class i f we want Mysql Connection, then we need t o modify the above program as follows.

ConnectionUtilizerOO2.iava 1. public class ConnectionUtilizerO02 { '

2. public static void main (String[] args) {

3 . System.out.println("this is Mysql Connection"); 4. 1 5. 1

d So when we want to get the services of other provider, we are modifying our utilizer class. + And in the above code we are mixing Utilizer code and Provider code. Means Utilizer is tightly

coupled with one particular provider. So, it is advisable to write different classes for Utilizer logic and Provider logic.

OracleConnectionProvider.iava 1. public class OracleConnectionProvider { . 2. public String getOracleConnection() {

3. return "this is oracle connection"; 4. 1 5. 1

Mvsa Icon nection Provider.iava 1. public class MysqlConnectionProvider {

2. public String getMysqlConnection () {

3. return "this is mysql connection"; 4. 1 5. 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 04023746666,23734842 An IS0 9001 : 2000 Certified Company

-. - . . - - . . - -- .. . -. -. . . . - . - - Page 1

http://javabynataraj.blogspot.com

Page 6: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- . .- - - ,

Spring-IOC -- -.. By Mr. SomasekharReddy(Certified Professiona!j :

ConnectionUtilizerOO3.iava 1. public class ConnectionUtilizerOO3 {

2. public static void main(String[] args) {

3 . OracleConnectionProvider oracleProvider = new 4. OracleConnectionProvider ( ) ;

5. String connectionstring = oracleProvider.getOracleConnection(); 6. System.out.println(connectionString); 7. 1 8. 1

* I f we want to get Mysql Connection in the above example, we need to create that particular provider object in our class(MysqlConnectionProvider.jav3). So, we have to modify the above program as follows.

ConnectionUtilizerOO4.iava 1. public class ConnectionUtilizerO04 {

2. public static void main(String[] args) {

3. MysqlConnectionProvider mysqlProvider = new 4. MysqlConnectionProvider ( ) ;

5. String connectionstring = mysqlProvider.getMysqlConnection(); 6. System.out.print~n(connectionString);

-.

7. 1 8 . 1

d I f we observe ConnectionUtilizerOO3, ConnectionUtilizerOO4 The way we are getting provider services is changing when the provider is changing. Means the way we are calling methods are

-I changing when provider is changing.

o To get Mysql Connection we are calling connection.getMysqlConnection(); - I

o To get Oracle Connection we are calling connection.getOracleConnection(); d To solve the above problem we should have a contract between service provider and service utilize. d I n java we can provide the contract with interfaces. I

d So the above program can be refador as follows. I Connection.iava 1. public interface Connection {

2. public String getconnection ( ) ; I e

3. 1 I 0racleConnectionProvider.iava 1. public class OracleConnectionProvider implements Connection {

2. public String getconnection () {

I I

3. return Itthis is oracle connectiontt: 4 . 1

I -

IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 ,I --- An I S 0 9001 : 2000 Certified Company - - - - - - - - - - - -- - - r

Page 2 http://javabynataraj.blogspot.com

Page 7: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

. - . . . . - -. . . . .--. - . . . . . -

Spring-IOC By Mr. SomasekharReddy(Certifie? Professional)

M~sqIConnectionProvider.iava 1. public class MysqlConnectionProvider implements Connection {

2. 3. public String getconnection ( ) {

4 . return "this is mysql connectionr1; 5. 1 6. 1

OracleConnectionProvider P

ConnectionUtilizerOO5.iava 1. public class ConnectionUtilizerOO5 {

2. public static void main (String[] args) {

3. Connection contract = new OracleConnectionProvider() ; 4 . String connectionstring = contract.getConnection() ; 5 . System.out.println(connection~tring);

6. 1 7 . 1

ConnectionUtilizerOO6.iava 1. public class Connectionutilizer006 {

2. public static void main (String[] args) {

3. Connection contract = new ~sqlConnectionProvider ( ) ;

4 . String connectionstring = contract.getConnection(); 5. System. out .println (connectionstring) ;

6. 1 7 . 1

I f we observe ConnectionUtilizerOO5, ConnectionUtilizerOO6 The way we are getting provider services is not changing even, when the provider is changing. Means the way we are calling methods are not changing when provider is changing.

o To get Mysql Connection we are calling contract.getConnection(); o To get Oracle Connection we are calling contract.getConnedion();

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- - - - - . . - An IS0 9001 : 2000 Certified Company -- - -- -

Page 3 http://javabynataraj.blogspot.com

Page 8: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

---- - ~

I Spring-IOC By Mr. SomasekharReddy[Certified Professional: 1 d Now i f we observe ConnectionUtilizer005, ConnectionUtilizerOO6 when the provider changing,

the we are creating that particular object in the utilizer class. d So, when the provider is changing we are modifying only one line of code( where we are creating

particular provider object). e As we know even i f we change one line of code, we need to recompile the application. So, when we

change the provider class we need to re-compile the application. So our Utilizer class is always need to change when the provider is changing.

d So we need to get the Provider object dynamically. d So we need t o specify our required provider declaratively. d To specify our requirements declaratively we use either properties file or xml file. e I n this example we specify, our requirements through properties file. d We w ~ l l write one container which will read our requirements and provide our required objects

dynamically.

Connectisn.iava 1. p u b l i c i n t e r f a c e Connection {

2 . p u b l i c S t r i n g getconnect ion ( ) ;

3. 1

OracleConnectionProvider.iava 1. p u b l i c c l a s s OracleConnectionProvider implements Connection {

2 . 3. p u b l i c S t r i n g getconnect ion ( ) {

4 . r e t u r n t h i s i s o r a c l e connection" ; 5. 1 6. 1

MvsqIConnectionProvider.iava 1. p u b l i c c l a s s MysqlConnectionProvider implements Connection {

2 . 3 . p u b l i c S t r i n g getconnect ion ( ) {

4 . r e t u r n " t h i s i s mysql c o n n e c t i ~ n ' ~ ;

5. 1 6. 1

MvContainer.iava 1 . import j ava . i o . IOException ; 2 . import j ava . u t i l . Prope r t i e s ; 3. 4 . p u b l i c c l a s s Mycontainer {

5 . p r i v a t e s t a t i c P rope r t i e s p r o p e r t i e s ; 6 . static {

7 . try {

8 . p r o p e r t i e s = new P r o p e r t i e s ( ) ; 9 . properties.load(ylContainer.class.getClassLoader~~ 10. . getResourceAsStream ("myproperties . p r o p e r t i e s w ) ) ;

11. ) ca t ch (IOException e) {

12. e . pr in tS tackTrace ( ) ;

13. 1 14. 1 15.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph:040-23746666,23734842 I . 1 L An I S 0 9001 : 2000 Certified Company

~ - -.- , .. .

Page 4, http://javabynataraj.blogspot.com

Page 9: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - -. - -- - - - - . . .

By Mr. SomasekharReddy(Certified Professional)

public static Object getBean (String providerKey) {

Object object = null; String providerClassName =

properties. getproperty (providerKey) ;

try t Class c = Class.forName(providerClassName) ; object = c.newInstance();

} catch (Exception e) {

e .printStackTrace ( ) ;

1 return object;

1

ConnectionUtilizerOO7.iava 1. public class ConnectionUtilizerOO7 {

2. 3. private static MyContainer container = new Mycontainer(); 4. 5. public static void main (String [ I args) {

6. Connection contract = (Connection) container. getBean ("provider") ; 7 . String connectionstring = contract.getConnection() ; 8 . System.out.print~n(connectionString); 9 . 1

Now if you want t o change the provider class, just change the properties file. We no need t o change the Utilizer class. Here we are implementing the container code. But in the case of spring, spring provides the container.

10. 1

Getting specified (in mypropertis.properties file) . Provider Object dynamically, by F \

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company I - - -- . . -- - - .- - -

Page 5

-

OracleConnectionProvider

Calling getBean( ...) method.To -this we are passing key of the provider class. , Mycontainer

Utilizer

5

Contract MysqlConnectionProvider 4

b

Specifying Required SomeOtherConnectionProvider

http://javabynataraj.blogspot.com

Page 10: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

r - - . -- - .

Spring-IOC By Mr. SomasekharReddy(Certified Professions;,' I ---

- ..- -. - r ,

First Examule on Surinq I

i. g& JRE .sy5tetll. Library js?,,; !.j ,)[jF : < , , . . i .... I 2 : -

(3 Spring 2.0 Core Libraries "

I Connection.iava 1. package com.neo.spring.contract; I 2. 3. public interface Connection { I 4 . -

5. public String getconnection () ;

6. 7 . 1

I MvsaIConnectionProvider.iava , 1. package com.neo.spring.provider; 2. 3. import com.neo.spring.contract.Connection; 4. 5. public class MysqlConnectionProvider implements Connection {

6. 7 . public String getconnection () {

8. return "this is mysql connectionw; 9. 1 10. 1

0racleConnectionProvider.iava 1. package com.neo.spring.provider; 2. 3. import com.neo.spring.contract.Connection; 4. 5. public class OracleConnectionProvider implements Connection {

6. 7 . public String getconnection () {

8. return "this is oracle connectionw; 9. 1 10. 1

ConnectionUtilizer.iava 1. package com.neo.spring.Utilizer; 2.

IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Companv

. . - -. - - - - -. . - - - - . . . Page 1,

http://javabynataraj.blogspot.com

Page 11: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- .- - -. -- - - -.

Spring-IOC By Mr. SomasekharReddy(Certified ProfessionaZ)

3. import org.springframework.beans.factory.BeanFactory; 4. import org.springframework.beans.factory.xml.XmlBeanFactory; 5. import org.springframework.core.io.ClassPathResource; 6. 7. import com.neo.sprlng.contract.Connection; 8. 9. public class Connectionutilizer {

10. private static BeanFactory factory = new XmlSeanFactory( 11. new ClassPathResource(llapplicationContext.xmlll)); 12. 13. public statlc void main(String[] args) {

14. 15. Connection contract = (Connection) 16. factory . getBean (I1provider"); 17. String connectionstring = contract.getConnection(); 18. System.out.println(connectionstring) ; 19. 1 20. 1

a~~licationContext.xml 1. <?xml version="l . O w en~oding=~~UTF-8~~?> 2. <beans 3. xmlns=11http://www.springframework.org/schema/beans11 4. xmlns : xsi=I1http: //www . w3. 0r~/2001/&~chema-ins tance~~ 5. xsi:schema~ocation=~~http://www.springframework.org/schema/beans 6. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd11> 7. < ! --<bean id="provider1I 8. class="com.neo.spring.provider.~y~q1ConnectionProvider~~/>--> 9. <bean id="providerI1 10. class=11com.neo.spring.provider.OracleConnectionProvider11/> 11. 12. </beans>

Primitive Data tv~e Constructor Iniection

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company L _- - _ - . - - -. _ - -. -

Page 2-- http://javabynataraj.blogspot.com

Page 12: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

.,,..',

2 [a Gr€~t i t i gEea l iU t i l i z~ l . , j a~ba

$15 applicat iat iCant~~.xml g g& JEE Sy~teni Libra1 x. & Spritiy Z,O Ccre Libraries

1. package com.neo.spring.bean; 2. 3. public class GreetingBean {

4. private String name ; 5. 6. public GreetingBean ( ) {

7. 1 8. 9 . Gree tingBean (String name) f 10. this.name = name; 11. 1 12. 13. public String getName() {

14. return name; 15. 1 16. 17. public void setName(String name) 18. this.name = name; 19. 1 20. 21. )

GreetincrBeanUtilizer.iava 1. package com.neo.spring.uti1izer; 2. 3. import org.springframework.beans.factory.BeanFactory; 4 . import org.springframework.beans.factory.xml.XmlBeanFactory; 5. import org.springframework.core.io.ClassPathResource; 6. 7 . import com. neo . spring. bean. GreetingBean; 8. 9. public class GreetingBeanUtilizeri 10. private static BeanFactory factory = new XmlBeanFactory( 11. new ClassPathEtesource (llapplicationContext. xmlI1) ) ; 12. 13. public static void main(String[] args) {

14. GreetingBean bean = (GreetingBean) factory . getSean (llgbw) ; 15. String name = bean. gewame () ;

16. System. out .println (I1Welcome to spring world : + name) ; 17. 18. 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 L

-- - - An IS0 9001 : 2000 Certified Company

- - - - - - . . . . -.

Page 3 http://javabynataraj.blogspot.com

Page 13: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

. .

By Mr. SomasekharReddy(Certified Professional) 1 19. 20. 1

au~licationContext.xml 1. <?xml version="l . O w enc~ding="UTF-E~~?> 2. <beans xmlns="http://www.springframework.org/schema/beans11 3. mlns:xs~="http://www.w3.org/2001/~Schema-instance11 4. xsi:schema~ocation="http://www.springframework.org/schema/beans 5. http://www.spr~ngframework.org/schema~beans/spring-beans-2.0.xsd11> 6 . <bean id="gbIf cla~s=~~com. neo . spring. bean. GreetingBeanvf> 7. <constructor-arg V ~ ~ U ~ = ~ ~ S O M A S E K H A R ~ ~ /> 8. 9. </bean> 10. 11. </beans>

I Primitive Datatvue Setter Iniection

r,. d, JRE System Library f S;i;-; JDM 1,6.0.-h3]

GreetinaBean.iava 1. package com.neo.spring.bean; 2. 3. public class GreetingBean {

4. private String name; 5 . 6. GreetingBeanO {

1 7. 8. 9 . GreetingBean (String name) {

10. this.name = name; 11. 1 12. 13. public String getName() {

14. return name ; 15. 1

16. publia void setName(String name) {

17. this.name = name; 18. 1 19. 20. 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040123746666,23734842

-- -- - - - -. . An IS0 9001 : 2000 Certified Company

Page 4 http://javabynataraj.blogspot.com

Page 14: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

By Mr. ~omas?l thar~eddy[~er t i f ied Professional-.- 1

GreetinqBeanUtilizer.iava 1. package com.neo.spring.ut~llzer; 2. 3. import org.springframework.beans.factory.Bean~; 4. import org.springframework.beans.factory.xml.Xm1BeanFactory; 5. import org.springframework.core.io.ClassPathResource; 6. 7. import com.neo.spring.bean.GreetingBean; 8. 9. public class GreetingBeanUtilizerj 10. prlvate static BeanFactory factory = new XmlBeanFactory( 11. new ClassPathResource (vvapplicationContext. xml") ) ; 12. 13. public statlc void main (String[] args) {

14. 15. GreetingBean bean = (GreetingBean) factory . getBean (tlgb") ; 16. String name = bean. geWame () ;

17. System. out. println ("Welcome to spring world: "+name) ; 18. 19. 1 20. 21. 1

a~~licationContext.xml 1 . < ? m l version="l. Ovv en~oding="UTF-8~~?> 2 . <beans xmln~=~~http : //www . springf ramework . org/schema/beansvt 3. xmlns:xsi=~http://www.w3.org/2OO1/~~~Schema-instance~~ 4. xsi:schemaLocation=~thttp://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-2.O.xsd~~> 5 . <bean id=vvgbvt cla~s=~~com. neo . spring. bean. GreetingBeanvr> 6. <property name=vrnamett v a l ~ e = ~ ~ s e k h a r ~ ~ / p r o p e r t y > 7. 8. </bean> 9. </beans>

*

Obiect tvpe Constructor Iniection

Naresh i Technologies, Opp. Satyam ~heat ie, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

-- - -. . . . - . - . An I S 0 9001 : 2000 Certified Company

-- Page 5

http://javabynataraj.blogspot.com

Page 15: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Spring-IOC By Mr. SomasekharReddy[Certified ~rofessional)

con~trcrctu1~Injecti0np1.oject02

s.rc

53 c0t-1-1.13%o.~pr1t1g.beat3

LS 2 cl cl 1.~5.5.j a 12.a

u-7 En~pIoye~.j~~,'a <, .,-+$ rotri,r ico,rpnng,ut~Ii i l~r

I " i& Err7 pIo;yc~Eea n Uti I irer.jaua. s-5 appIicationConte&.xmI

& i ~ J E E S y s t t t t ~ ~ L i b r a r y : ' - ' , c ,k l ,&.3-3i ,E&& Spring 2.0 Core Libraries

Address.iava 1. package com.neo.spring.bean; 2. 3. public class Address {

4 . private int hno; 5 . private String city; 6. 7. public Address ( ) {

8. 1 9. 10. public Address (int hno, String city) {

11. this.hno = hno; 12. this.city = city; 13. 1 14. 15. publlc int getHno() {

16. return hno; 17. 1 18. 19. public void setHno(int hno) {

20. this.hno = hno; 21. 1 22. 23. public String getcity() {

24. return city; 25. 1 26. 27. public void setCity(String city) {

28. this-city = city; 29. 1 30. 31. )

Em~l0vee.iava 1. package com.neo.spring.bean; 2. 3. public class Employee {

4 . private int eno ; 5. private String ename; 6 . private Address address ; 7. 8 . public Employee () {

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

- - -- - -. . . - .- - - - -- - - -. Page 6

http://javabynataraj.blogspot.com

Page 16: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- .- . - - -- -. - - - -

S~ring-IOC Bv Mr. SomaseltharReddv(Certified ProfessionaF7

public Employee(int eno, String ename, Address address) {

this.eno = eno; this.ename = ename; this.address = address;

1

public int getEno ( ) {

return eno;

1

public void setEno (int en01 {

this .en0 = eno; 1

public String gemname() { return ename;

1

public void setEname(String ename) { this.ename = ename;

1

public Address gewddress 0 {

return address ; 1

public void se-ddress (Address address) {

this-address = address;

1 1

Em~loveeBeanUtilizer.iava 1. package com.neo.spring.uti1izer; 2. 3. import org.springframework.beans.factory.BeanFactory; 4. import org.springframework.beans.factory.xml.XmlBeanFactory; 5. import org.springframework.core.io.ClassPathResource; 6. 7. import com.neo.spring.bean.Address; 8 . import com . neo . spring. bean. Employee ; . 9. 10. public class EmployeeBeanUtilizer{ 11. private static BeanFactory factory = new XmlBeanFactory( 12. new ClassPathResource ( llapplicationContext. xniLV1) ) ; 13. 14. public static void main (String[] args) { - 15. System. out .println ("Employee details. . . 'I) ; 16. Employee employee = (Employee) factory . getBean (llemployeell) ;

17. System. out .println (employee. getEno ( ) ) ;

18. System.out.println(employee.getEname()); 19. Address address = employee.getAddress ( ) ; 2 0 . Sy~tern.out.println(~~Employee address details ...I1) ; 21. System. out .println (address .getHno ( ) ) ;

- - - - - - - - - - -

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

An I S 0 9001 : 2000 Certified Company - -. - -- - , -- -- - .. . - .- . - . . - -- - -- -. . - . . - . . . Page 7

http://javabynataraj.blogspot.com

Page 17: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - --

Spring-IOC By Mr. SomasekharReddy[Certified Professional)

22. System. out.println (address. getcity ( ) ) ;

23. 1 24. 1

applicationContext.xml 1 . <?xml version="l. 0" en~oding=~'UTF-8~~?> 2. <beans xmlns=11http://www.springframework.org/schema/beans11 3 . xmlns:xsi=11http://www.w3.org/2O01/XMLSchema-instance11 4. xsi:schemaLocation=1'http://www.springframework.org/schema/beans 5 . http://www.~pringframework.org/schema/beans/spring-beans-2.0.xsd~~> 6. 7. <bean id="addrw class=llcom.neo.spring.bean.Addressll> 8. <constructor-arg ~alue=~~1702" /> 9. <cons tructor-arg value=I1Hyderabadl1 /> 10. </bean> 11. <bean id="employeel' class=llcom.neo.spring.bean.Employeell> 12. <constructor-arg ~alue=~88688~' /> 13. <constructor-arg ~alue=~~sekhar" /> 14. <constructor-arg ref="addrI1 /> 15. </bean> 16. 17. </beans>

Obiect tvve Setter Injection r "g z~tterlt i j t c t i on PI-oj ecV22

a @ src A @ coni,tiea.spri~ig.L-~eati

: 5 i 3 &dclre~s.java

:, jg Emplcyce,jaqda

d a ccm.tico,r-pt-inc~~utiliier

:, ia En-rployeeBeatiUtilizer.java

$;? applicatiorrContc&.xmI

v & JRE Systerri L~hraty [ E t - ~ . > ! I 4 1,5,0-13] p & Sprincj 2,0 Core Libra1.i~~

1 1 . package corn. neo . spring. bean ; 2. 3. public class Address {

4. private int hno; 5. private String city ; 6. 7 . public Address ( ) {

8. I 9. 10. public Address(int hno, String city) {

11. this.hno = hno; 12. this.city = city; 13. 1 14. 15. public int getHno() {

16. return hno ; 17. 1 - -

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

- . .- - . . . . - - - . .. . . . . . . . -- - Page 8

http://javabynataraj.blogspot.com

Page 18: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- - -- -

Spring-IOC By Mr. ~ornase l thar~eddy(~er t i f i ed Professional-'

public void setHno (int hno) { this.hno = hno;

I

public String getcity() {

return city;

I

public void setcity (String city) {

this. city = city; I

I

1. package com.neo.spring.bean; 2. 3. public class Employee {

4. private int eno; 5. private String ename; 6. private Address address ; 7. 8 . public Employee ( ) {

9. 1 10. 11. public Employee(int eno, String ename, Address address) {

12. this.eno = eno; 13. this.ename = ename; 14. this.address = address; 15. I 16. 17. public int getEno 0 {

18. return eno; 19. I 20. 21. public void setEno(int eno) {

22. this.eno = eno; 23. 1 24. 25. public String getEname() {

26. return ename; 27. I 28. 29. public void setEname (String ename) {

30. this-ename = ename; 31. 1 32. 33. public Address getAddress0 {

34. return address; 35. 1 36. 37. public void setAddress (Address address) {

38. this.address = address; 39. I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 l

An IS0 9001 : 2000 Certified Company - - - - - - - - - - - . . - -

Page 9 http://javabynataraj.blogspot.com

Page 19: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - -- - . - - .

Soring-IOC By Mr. SomasekharReddy[Certified Professional)

Em ~ l~~eeBeanUt i l iZer . i a~a 1. package com.neo.spring.utllizer; 2. 3. import org.springframework.beans.factory.BeanFactory; 4. import org.springframework.beans.factory.xml.XmlBeanFactory; 5. import org.springframework.core.io.ClassPathResource; 6. 7. import com.neo.spring.bean.Address; 8. import com.neo.spring.bean.Emp1oyee; 9. 10. public class EmployeeBeanUtilizer{ 11. private static BeanFactory factory = new XmlBeanFactory( 12. new Clas sPathResource ( "applicationContext . xml ") ) ; 13. 14. public static void main (String[] args) {

15. System.out.println(~Employee details..."); 16. Employee employee = (Employee) factory. getBean (llemployeell) ;

17. System.out.println(employee.getEno()); 18. System.out.println(employee.getEname()); 19. Address address = employee.getAddress(); 20. System.out.println(~'Employee address details..."); 21. System.out.println(address.getHno()); 22. System. out .println(address .getcity () ) ;

23. 1 24. 25. 1 26.

1 . <?xml versi~n=~~l. 0" encoding="UTF-8"?> 2 . <beans xmlns="http : //www . springf ramework . org/schema/beansv~ 3. xmlns:xsi=~~http://www.w3.org/20O1/XM~Schema-instance~~ 4. xsi:schema~ocation=~~http://www.springfraework.org/schema/beans 5. http://www.springframework.org/schema/beans/spring-beans-2.O.xsdw> 6. 7. <bean id=lfaddrfl class="com . neo . spring. bean .Addresstv> 8. <property name=lVhnof8 ~alue=~~187 95IvX/property> 9. <property name="ci ty If val~e=~~Hyderabad~X/property> 10. </bean> 11. <bean id="employeen class=~com.neo.spring.bean.Ernp1oyeew> 12. <property name="enon ~alue=~lOl~~/property> 13. <property name=rvenamerl val~e=~~sekhar"~/property> 14. <property name="addres~~~ ref =I1addr"X/property> 15. </bean> 16. </beans>

Naresh i Technologies, Opp. Satyam s heat re, ~ m e e r ~ e t , ~~derabad,~h: 0%-23746666,23734842 An IS0 9001 ; 2000 Certified Company

........ ..... -~

Page 10 http://javabynataraj.blogspot.com

Page 20: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

--

By Mr. SomasekharReddyfCertified Professional_'

IOC Example

i2 * s ,....+ ,ia TransportaionZonstructorInjection . .

(d -@ src . , ....

i7J corn. neu .sping.client r-5

& - client, java . . i i i 3.. , @J corn ,neu,sping,contract ! ! . , .

, . , i . [ g , Transport, jma ' > t . .

i a.--@j com.neo,sping,custorner . . . . , . . '5 , . , !'& . - Transportcustomer, java

: . 3 . &j com,neo, sping.provider . . . . i i @ ~ ivakar~ rave ls . java

: . ! .

i i i El,,- @ KesineniTravels, java : i : . .

: ',, ,@ applicationcontext ,xml . ,

: [$i:I.-.&& JKE System Library [!,.s~,::.~:~~..j .5] i &-E& Spring 2,5 Core Libraries

,..>

Client.iava -

1. package com.neo.splng.client; 2. 3. import org.springframework.beans.factory.BeanFactory;

-

4. import org.springframework.beans.facto~.xml.XmlBeanFactory; 5. import org.springframework.core.io.ClassPathResource; L

6. 7. import com.neo.sping.customer.TransportCustomer; 8. 9. public class Client {

10. private static BeanFactory factory = new XmlBeanFactory( 11. new ClassPathResource ("applicationContext . xmlql) ) ;

12. i 13. public static void main(String[] args) {

14. TransportCustomer customer = (TransportCustomer) 15. factory . getBean ( "tc"); 16. customer.useTransport(); 17. 1 18. 1

Transuort.iava 1. package com.neo.sping.contract; 2. 3. public interface Transport {

4. void dolravel ( ) ;

5. 1

Trans~ortCustomer.iava 1 . package com . neo . sping . customer ; 2. 3. import com.neo.sping.contract.Transport; 4. 5. public class TransportCustomer {

6.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 ,

- - - - - - - - An IS0 9001 : 2000 Certified Company -

Page 1 http://javabynataraj.blogspot.com

Page 21: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

. . . . - -

Spring-IOC By Mr. SomasekharReddyfCertified Professional)

private Transport transport;

public Transportcustomer() {

1

public TransportCustomer(Transport transport) {

this.transport = transport; 1

public void setTransport(Transport transport) {

this.transport = transport; 1

public void useTransport() {

transport. doTravel () ; 1

1

DivakarTravels.iava 1. package com.neo.sping.provider; 2. 3. import com.neo.sping.contract.Transport; 4. 5. public class DivakarTravels implements Transport {

6 . public DivakarTravels () {

7. 8. 1 9. 10. public void doTravel ( ) {

11. System.~ut.println(~~this is best DivakarTravels, happy journy"); 12. 1 13. )

KesineniTravels.iava 1. package com.neo.sping.provider; 2. 3. import com.neo.sping.contract.Transport; 4. 5. public class KesineniTravels implements Transport {

6 . public KesineniTravels () {

7. 1 8. 9 . public void doTravel () {

10. System.out.println("this is very best KesineniTravels, have a 11. nice j o~rney~~) ; 12. 1 13. }

a~~licationContext.xrnI 1. <?d version=I1l. 0" encoding="UTF-8"?> 2 . <beans xmlns=I1http : //www . springframework. org/~chema/beans~~ 3. xmlns:xsi=11http://www.w3.org/2OO1/XMLSchema-instance11 4 . xmlns :p=I1http: //www . springf ramework. org/s~hema/p~~ 5 . xsi:schemaLocation="http://www.sprin~fr~ework.org/schema/beans

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

L ~ ~

~ a s - http://javabynataraj.blogspot.com

Page 22: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Bv Mr. SomasekharReddv(Certified Professional"

6. http://www.springframework.org/schema/beans/spring-be~s-2.5.x~d~~> 7. 8. <bean id="dtI1 class=~com.neo.sping.provider.DivakarTravel~~~X/bean> 9. <bean id="ktM class=11com.neo.sping.provider.KesineniTravels11~/bean> 10. 11. <bean id="tcW class=1~com.neo.sping.customer.Tran~portCustomer1~> 12. <cons tructor-org ref="dtI1/> 13. . </bean> 14. </beans>

. .

TranspurtaionSetterIr~jeition ri) . . . ,.@ .'".. src

. . i . 8..-@ . com,neo,spir~g,clier~t . , . : . , . . 3. Client, java < . . : [$. . . . .@ < . .

com,neo,sping,ior~tract , . , . 3. a Transport, jamyma

, , . . ; . 6-B . com,neo,sping,a~stomer . ,

i 33 .g TransportCustomer, java . . : <

, i , . 6-43 . com,neo,sping, provider 1 , . . . , ~

I Bk.-.. DivakarTravels, java , . ! , . , . i ; 3.. KesineniTravell;. java ; ;

: : $5 ; :,..,$* applicationContext, xml $!--&$ JRE system Library !,.ja.,;;.;SE ... 1 . . - : :

i3.a 5pring 2,s Core Libraries

Client.iava 1. package com.neo.sping.client; 2. 3. ircport org.springframework.beans.factory.BeanFactory; 4. import org.springframework.beans.factory.xml.XmlBeanFactory; 5. import org.springframework.core.io.ClassPathResource; 6. import com.neo.sping.customer.TransportCustomer;

-

7. 8. public class Client {

9. private static BeanFactory factory = new XmlBeanFactory( 10. new ClassPathResource(~applicationContext.xml~)); 11. 12. public static void main(String[] args) {

13. TransportCustomer customer = (Transportcustomer) 14. factory. getBean ( "tcw) ; 15. customer.useTransport(); 16. 1 17. )

Trans~orLiava '1. package com.neo.sping.contract; 2. 3. public interface Transport {

4. void doTravel ( ) ;

5. 1

IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 i

-- An I S 0 9001 : 2000 Certified Company - - - . - - - -- . . .- - .- - . . . . - . . -

Page 3 I

http://javabynataraj.blogspot.com

Page 23: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Trans~ortCustomer.iava 1. package com.neo.sping.customer; 2. 3. import com.neo.sping.contract.Transport; 4. 5. public class Transportcustomer {

6. 7. private Transport transport; 8. 9. public Transportcustomer ( ) {

10. 11. 1 12. 13. public TransportCustomar(Transport transport) 14. this.transport = transport; 15. 1 16. 17. public void setTransport(Transport transport) 18. this.transport = transport; 19. 1 20. 21. public void useTransport() { '

22. transport. doTravel ( ) ; 23. 1 24. 1

DivakarTravels.iava 1 . package com . neo . sping . provider ; 2. 3. import com.neo.sping.contract.Transport; 4. 5. public class DivakarTravels implements Transport {

6. public DivakarTravels ( ) {

7. 8. 1 9. 10. public void doTravel ( ) { 11. System.~ut.println(~~this is best DivakarTravels, happy 12. j ourny") ; 13. 1 14. )

KesineniTravels.iava 1. package com.neo.sping.provider; 2. 3. import com.neo.sping.contract.Transport; 4. 5. public class KesineniTravels implements Transport {

6 . public KesineniTravels ( ) {

7. 1 8. 9 . public void doTravel0 {

10. System.~ut.println(~~this is very best KesineniTravels, have a 11. nice journey") ; 12. 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company

-- - - Page 4

http://javabynataraj.blogspot.com

Page 24: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Bv Mr. SomasekharReddvfCertified professionall? I

ap~licationContext.xml 1. < ? m l version="l . O H encoding="UTF-811?> 2. <beans mlns="http://www.springframework.org/schema/beans11 3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance11 4 . mlns:p=1'http://www.springframework.org/schema/p~1 5. xsi:schemaLocation="http://www.springfrework.org/schema/beans 6. http://www.springframework.org/schema/beans/spring-beans-2.5.x~d~~> 7. 8. <bean id="dtW ~lass=~~com.neo.sping.provider.Divakar~ravels~~~/bean> 9. <bean id="ktI1 cla~s=~~com. neo. sping. provider. Kesineni~ravelsI~></bean> 10. 11. <bean id=l1tcl1 ~lass=~~com. neo. sping .customer. TransportCustomerl'>

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company

-- - -. - - . -. . .- -.

Page 5 http://javabynataraj.blogspot.com

Page 25: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

. - - - - -- . - .

Spring-I OC By Mr. SomasekharReddy(Certified Professional)

.. 7;s d v "e LayerCon~tructorInjection

c&-& IRE System Library [.3s,..?afE-:! .6]

Spring 2.5 Core Libraries &j...Kq xi.. s,c

' *-. T2-rn cori~, nen. spring.client

. . . . *-*

i ixl. @ Test, ja..ta

&&-f&: com.np,n.5pring,dao Lii, "J

> . / J Dao. java

. -.

j $xi.- [-$ DaoImpl , java El..,@ cum, neo , spring service

&.- a Service. java . . : , i l % . D.7 ServiceImpl. java

!S-.@l- . . com.neo .spring.servlet ; servlet. java

! I& .. BS ServletIrnpl, java jl.,l..

: . P.3 applicationContext,xml

Test.iava 1 . package corn. neo . spring. client; 2. 3. import org.springframework.beans.factory.BeanFactory; 4. import org.springframework.beans.factory.wnl.XmlBeanFactory; 5. import org.springframework.core.io.ClassPathResource; 6. 7. import com.neo.spring.servlet.Servlet; 8 . 9. public class Test {

10. private static ~ean~actory factory = new XmlBeanFactory( 11. new ClassPathResource ( "applicationContext .3unl") ) ; 12. 13. public static void main (String[] args) {

14. Servlet servlet = (Servlet) factory. getBean ("servletref If) ; 15. servlet . servletMethod () ; 16. 1 17. 18. )

Dao.iava 1. package com.neo.spring.dao; 2. 3. public interface Dao {

4. public void daoMethod0; 5.

DaoIm~l.iava 1 . package com . neo . spring. dao ; 2. 3. public class DaoImpl implements Dao{ 4 . public DaoImpl () {

- - - -

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 An IS0 9001 : 2000 Certified Company

. ~

Page 1 http://javabynataraj.blogspot.com

Page 26: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

. - -- - - - - -- - - - --

pigr -. -. - - - - . .- -. .. -- - . By Mr. SomasekharReddy(Certified Professiona., --

5. 1 6. public void daoMethod() {

7. System. out .println ("This is DAO layer") ; 8. 1 9. 1

Service.iava 1. package com.neo.spring.service; 2. 3. public interface Service {

4. public void serviceMethod ( ) ; 5 . 1

ServiceIm~l.iava 1. package com.neo.spring.service; 2. 3. import com.neo.spring.dao.Dao; 4 . 5 . public class ServiceImpl implements Service {

6. private Dao dao; 7 . public ServiceImpl() {

8. 1 -

9. public ServiceImpl (Dao dao) {

10. this.dao=dao; L

11. 1 12. public void setDao(Dao dao) {

13. this.dao = dao; 14. 1 15. 16. public void serviceMethod() {

17. System. out .println ("This is Service Layer") ; 18. dao . daoMethod ( ) ; 19. 1 20. 1 6

Servlet.iava 1. package com.neo.spring.servlet; 2. 3. public interface Servlet {

4 . public void servletMethod () ;

5 . 1

ServletIm ~l.iava 1. package com.neo.spring.serv1et; 2. 3. import com.neo.spring.service.Service; 4 . 5 . public class ServletImpl implements Servlet {

6 . private Service service; 7 . public ServletImpl ( ) {

8. 1 9. publicServletImpl(Serviceservice) {

10. this.service=service; 11. 1 12. public void setservice (Service service) {

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 (

An IS0 9001 : 2000 Certified Company

http://javabynataraj.blogspot.com

Page 27: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - . - . By Mr. SomasekharReddy(Certified Professional) .

- -

13. this.service = service; 14. 1 15. public void servletMethod() {

16. System. out. println ("This is presentaion layer") ; 17. service. serviceMethod ( ) ;

18. 1 19. 20. 1

LayerSetterInjection , .

i @ ,@ 5rc . i . . 3- @ com,neo,spring,client . . ,

. . ~. I . i 1% @ Test. java > : ~

i , . . a-@coni,neo.spring,dao , : . . . . . . . . W a Dao,java 2 . :

; i @,.G DaoImpl.java ! ! . , . : , . . Ed-..@ com,neo.spring,service < : , ,

. . . . / @ . Service. java . . . . . . . . . . . . . . . . . . i &I @ ServiceImpl,java

' . . . . j [$.. @ coni,neo .spring ,servlet

. . . , . . i id @ Servlet. java . . .

< . , . . . i . i . i 5ervletIrnpl.java 3 : ; . , . . . . . . . . . ~ . . * :

'-..,:&s applicationcontext, xml

@...a :IRE System Library [JavsSE.. b ,43 , I Spring 2.5 Core Libraries

Test.iava 1. package com.neo.spring.client; 2. 3. import org.springframework.beans.factory.BeanFactory;

Naresh i Technologies, Opp. satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Com~anv

. . . -- -. -. .. .- . ,

Page 3 http://javabynataraj.blogspot.com

Page 28: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- -- - . . . . . . - . .- - -. . . -.

~ O C - By Mr. SomasekharReddy[Certified ProfessionalJ -1 4. import org.springframework.beans.factory.xml.XmlBeanFactory; 5. import org.springframework.core.io.ClassPathResource; 6. 7. import com.neo.spring.serv1et.Servlet; 8. 9. public class Test {

10. private static BeanFactory factory = new XmlBeanFactory( 11. new ClassPathResource (llapplicationContext. xmll1) ) ;

12. 13. public static void main(String[] args) {

14. Servlet servlet = (Servlet) factory. getBean (llservletref 11) ; 15. servlet. servletMethod() ; 16. 1 17. 18. 1

Dao.iava 1. package com.neo.spring.dao; 2. 3. public interface Dao {

4. public void daoMethod() ; 5. 6. 1

DaoImel.iava 1 . package com . neo . spring. dao ; 2. 3. public class DaoImpl implements Dao{ 4. public DaoImpl ( ) {

5. 1 6. public void daoMethod() {

7 . System. out .println ("This is DAO layer") ; 8. 1 9. 1

Service.iava 1 . package com . neo . spring. service ; 2. 3. public interface Service {

4 . public void serviceMethod() ;

5 . 1

ServiceImpl.iava 1 . package com . neo . spring. service; 2. 3. import com.neo.spring.dao.Dao; 4. 5. public class ServiceImpl implements Service {

6 . private Dao dao ; 7. public ServiceImpl() {

8. 1 9 . public ServiceImpl (Dao dao) {

10. this.dao=dao; 11. 1 12. public void setDao (Dao dao) {

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- -. - - . -- - - - - - An IS0 9001 : 2000 Certified Company I Page 4

http://javabynataraj.blogspot.com

Page 29: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Bv Mr. SomasekharReddvfCertified Professionali

13. this.dao = dao; 14. 1 15. 16. public void servi ceMethod ( ) {

17. System.out.println("This is Service Layern); 18. dao . daoMethod ( ) ; 19. 1 20. 1

Servlet-iava 1 . package corn. neo . spring. servlet ; 2. 3. public interface Servlet {

4 . public void servletMethod();

5. 1

ServletImpl.iava 1 . package corn. neo . spring. servlet ; 2. 3. import com.neo.spring.service.Service: 4. 5. public class ServletIrnpl implements Servlet {

6. private Service service; 7 . public ServletImpl ( ) {

8. 1 9 . public ServletImpl (Service service) {

10. this.service=service; 11. 1 12. public void setservice (Service service) {

13. this.service = service; 14. 1 15. public void servletMethod() {

16. System.~ut.println(~This is presentaion layer"); 17. service. serviceMethod ( ) ;

18. 1 19. )

a- 1 . <?xml version="l .Oft enc0ding=~~UTF-8"?> 2. <beans xmlns=~~http://www.springframework.org/schema/beans~~ 3. xmlns:xsi=~~http://www.w3.org/2001/XMLSchema-instance~~ 4. xmlns:p=~http://www.springframework.org/schema/p~~ 5. xsi:schema~ocation="http://www.springfrmework.org/schema/beans 6. http://www.springfrmework.org/schema/beans/spring-beans-2.5.xsd~~> 7. 8. <bean id="daorefw1 class="com.neo.spring.dao.DaoImpl"> 9. </bean> 10. <bean id="serviceref clas~=~~com. neo . spring. service. ServiceImplnv> 11. <property name=lldaow ref="daorefWX/property> 12. </bean> 13. <bean id=llservletref class="com. neo . spring. servlet . ServletImplI8> 14. <property name="servicew ref=lwservicerefnX/property> 15. </bean> 16. 17. </beans>

Nares11 i Technologies, Opp. Satyam ~heat ie, Ameerpet, ~yderabad, Ph: 040-23'746666; 23734842 An IS0 9001 : 2000 Certified Company

- - - - -. - - . . - Page 5

http://javabynataraj.blogspot.com

Page 30: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

j a%ed

1 - . . - - - - -- --

hueduo3 pa!4!W3 0002. : 1006 OSI u t l 7

c ' L ! () aoymasBa~uoNqa6 pyoh qoexqsqe 3y~qnd g

' S ! () aoyhyxas6a~qa6 pyoh qoexqsqe oy~qnd - p

) nuax aoegxaquy o ~ ~ q n d ' E ' Z

!qoexquoo~6u~xds~oau~moo a6eyoed .T eneimnuaw

' 2 ! xamoqsno 6urxds. oau -moo a6eqaed T

enr?!-.mwoasn3baA

I 'PT C ' ET

! () aormaspoo.~qa6 - xauxoqsno ' ZT ! (,, xamoqsno,, ) ueaaa6 -boqoeg (xamoqsn3) = xamoqsno xamoqsn3 'TT

) (s6xe [ I 6urxqs) urem proh orqeqs or~qnd OT '6

! ( (,,~nrx-6~3uoo-6uyxds,,) aoxnosaxqqedsse~3 ~ a u ' 8 )boqoedueaaT?nx Mau = b o q o e ~ boqoe,gueaa orqeqs aqen~xd ' L

quaTT3 SseTo o ? T ~ d '9 !xamoqsn~~qoexquoo~6u~xds~oau~moo qxodmy ' s

! a o ~ n 0 ~ a ~ ~ e d ~ ~ e ~ 3 ' 0 ~ ~ a ~ 0 3 ~ ~ ~ 0 ~ a ~ ~ 3 6 ~ ~ d ~ 6 0 qxoduxy 'P !~oqoeguea~~~'~~'fioqoeg'sueaq~yxo~aurexg6u~xds'6xo qxoduxy 'E

! ~ o q o e ~ u e a ~ ' b o q o e ~ 3 ~ ~ e a q g y x o ~ a ~ x g 6 ~ ~ x d s 6 x o qxodnrr '2 !quay~o -6urxds. oau-moo a6eyoed T

:enejmaua!13

.

http://javabynataraj.blogspot.com

Page 31: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

r - -. - - - . - -- -- -

Spring-IOC By Mr. SomasekharReddy(Certified Professional)

4. import com. neo . spnng . contract. Menu; 5. 6. publlc class VegCustomer implements Customer {

7. 8. prlvate Menu menu ; 9. 10. publlc vold setMenu (Menu menu) {

11. this.menu = menu; 12. 1 13. 14. @ Overrlde 15. public vold getFoodService() {

16. 17. menu.getVegSer~vice(); 18. 19. 1 20. 1

NonVesCustomer.iava 1 . package com . neo . spring. cus tomer ; 2. 3. import com.neo.spring.contract.Customer; 4. import com.neo.spring.contract.Menu; ' 5. 6. public class NonVegCustomer implements Customer {

7 . private Menu menu ; 8. 9 . public void setMenu (Menu menu) {

lo. this.menu = menu: 11. 1 12. 13. @Override 14. public void getFoodService0 {

15. 16. menu.getNonVegService(); . 17. 1 18. }

BlueFoxRestau rant.iava 1. package com.neo.spring.provider; 2. 3. import com.neo.spring.contract.Menu; 4 . 5 . public class BlueFoxRestaurant implements Menu {

6. 7 . @Override 8 . public void getvegserivice () {

9. System. out .println (vlBlueFoxRestaurant best veg servicev1) ; 10. 11. 1 12. 13. @Override 14. public void getNonVegService () . { 15. System.out.println("BlueFoxRestaurant worst non-veg service1'); 16. - - - - - - - -- - - - -- - - - - - - -

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

--A

An I S 0 9001 : 2000 Certified Company - - - - . - -- - - -

Page 2 http://javabynataraj.blogspot.com

Page 32: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

ParadiseRestaurant.iava 1. package com.neo.spring.provider; 2. 3. import com.neo.spring.contract.Menu; 4. 5. public class ParadiseRestaurant implements Menu {

6. @Override 7. public void getVegSerivice ( ) {

8. 9. Sy~tem.out.println(~~ParadiseRestaurant worst veg servicen); 10. 11. 1 12. 13. @Override 14. public void getNonVegService ( ) {

15. 16. System. out. println (ItParadiseRestaurant best non-veg servicett) ; 17. 18. 1 19. )

sprinq-conficl.xml 1 . <?xml version= "1.0" encoding= "UTF-a"?> 2 . <beans xmlns= "h t tp : //m. springframework. org/schema/beans " 3. xmlns : xsi= "http: //www. w3. org/20Ol/XMLSchema-instance" 4 . xmlns : p= "h t tp : //www. springframework. o~-~/schema/~ " 5. xsi:schemaLocation="http://wkrw.springframework.org/schema/beans 6 . h t tp : //m. springframework. org/schema/beans/spring-beans-2.5. xsd "> 7. 8. < ! provider configuration --> 9 . <bean id= 'lparadiseref" 10. class="com.neo.spring.provider.ParadiseRestaurant"X/bean> 1 1 . <bean id= "bl uefoxref" 12. class= "corn. neo . spring. provider. BlueFoxRestaurant bean> 13. 14. <!-- customer configuration --> 15. <!-- 16. <bean id=ttcustomerrt ~lass=~~com. neo . spring. customer .VegCustomerIt> 17. <property na~ue=~'menu">

</bean> -->

<bean id= "customer " class= "com. neo . spring. customer. NonVegCustomer "> <property name= "menu

<ref bean="paradiserefW /> </property>

</bean> </beans>

-- IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- - - - - - - --- - An IS0 9001 : 2000 Certified Company - -

Page 3 http://javabynataraj.blogspot.com

Page 33: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - - -- - .. -- - - - - .-

Spring-I OC By Mr. SomasekharReddyrCertified Professional)

IOC terminology

int sno ;-b Dependency String sname; Address address;. Dependency / / setters & getters

userdefined datatypes.

Class Address {-b Dependent int hno ;- Dependency String street; / / setters & getters

1

Q) How many ways we can give a value for dependencies? I n two ways:-

9 Constructor Approach 9 Setter Approach

9 Here the dependencies can be primitive datatypes or primitive object

Constructor Approach:

tvues o r

Address.iava public class Address {

Student.iava public class Student {

private int sno ; private String sname; private Address address; public Student(int sno, String sname, Address address) {

Using constructor give the values t o the dependencies. Address add=new Address () ; Student student=new Student (1001, sekharr ,add) ;

Setter Approach:

Address.iava public class Address {

Student.iava public class Student {

private int sno ; private String sname; private Address address; public Student(int sno, String sname, Address address) I

this.sno=sno; this.sname=sname;

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- - - - - - . . - - - An IS0 9001 : 2000 Certified Company

Page 4 http://javabynataraj.blogspot.com

Page 34: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - -- - -

1 Spring-IOC Bv Mr. SomasekharReddvCCertified Professional' -'I

this.address=address; 1 public Student ( ) {

1 public int getSno ( ) {

return sno; 1 public void setsno (int sno) {

this.sno = sno; 1 public String getSname() {

re turn sname;

1 public void setsname (String sname) {

this.sname = sname; 1 public Address getAddress0 {

return address; 1 public void setAddress(Address address) {

this.address = address; 1

1

Using setter methods giving the values to the dependencies. Address address=new Address ( ) ; Student s tuden t=new Student ( ) ; student.setSno (1001) ; student. sname ( 'sekhar') ;

student. setAddress (address) ;

> Here we are writing default constructor to create the student object without passing any constructor arguments (to go for setter approach).

> Here we are writing the setter methods to give the values to dependencies . > Here we are writing getter methods to access the values of dependencies. For setter approach z,

actually getter methods are not required.

Q) What is IOC? Ans: Inversion Of Control is a design principle using which an external entity injecting dependencies into dependent objects. In Spring, Spring Container is the external entity, which injects dependency objects into dependent object.

Q) What is DI? Ans:

Physical realization of IOC is nothing but D I (Dependency Injection). Resolving the dependencies of among the beans is nothing but Dependency Injection. I n case of spring , dependencies are injected into dependent object (beans ) through D I by spring container. I n spring D I is generally achieved in 2 ways, r-

1) setter injection . 2) constructor injection. I n a well designed spring bean, interfaces are specified as dependencies. I f dependency is provided to dependent object via setter method , it is known as setter injection. , I f dependency is provided to dependent object via constructor, it is known as constructor injection.

Q.) What are the Benfits of Dependency Injection? - Naresh i Technologies, Opp. Satyam Theatt'e, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- - -- - - - - - -- . - . An IS0 9001 : 2000 Certified Company

r i A

Page 5 http://javabynataraj.blogspot.com

Page 35: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Bv Mr. SomasekharReddv(Certified Professionall

Ans: 1.) Dynamically we can change dependency objects. 2.) Even dependency changing dependent object code remains same, there by it is offering loose

coupling among dependent and dependencies.

Q.) What is Spring Bean? Ans: Java class that are controlled by spring container are known as Spring Bean.

Q.) Which injection is better? Ans: Setter injection is always preferable because we can change the dependency value any no. of times as we required. But with constructor we can't change dependency object value, as and when we require.

Steps involved in Sprinq A~ulication ~eveloument:

> Develop the Spring beans(c1asses) according to the Bussiness requirement. > Develop the spring configuration file and configure the spring beans developed in stepl. 3 Inject the dependencies into dependent objects either in setter approach (identify how the bean is

expecting Dependency object values based on that we are going to define either of one). > Create the instance of spring container. > Get the instance of dependent objects from the container by making a method call getBean(), by

passing id of a bean. 3 After we get the bean object we will call the required methods on dependent bean.

Q) How to implement setter injection in a spring container? Ans: Step 1: I n spring bean class declare the dependency variable. Step 2: Define setter method for that variable. Step 3: Use <property > tag in bean configuration file & supply the value. 9. Example for Setter iniection where deuendencv is ~r imit ive tvue:

public class Purse{ private double money; public void setMoney(double money){

this.money=money;

Spring configuration file: <beans ... >

<bean id="pursem class="Purse"> <property name="moneyW vaIue="lO"></property>

(or) <property name="money" value="lO"/>

(or) <property name="money">

< value> lO</value> </property>

</bean> </beans>

E x a m ~ l e for Setter iniection where deuendencv is obiect tvue: public class Provider { 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

- . - - - - . -- - -- - - -.

Page 6 http://javabynataraj.blogspot.com

Page 36: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Bv Mr. SomasekharReddvfCertified Professional-'

public class Customer{ private Provider provider; public void setProvider(Provider provider){

this.provider= provider; 1

Spring configuration file: <beans ... >

<bean id ="p" class= "Providert'/> <bean id ="c" class="Customer">

<property name="providerU ref="pU></property> (or)

<property name="providerU ref="pt'/> (or)

<property name="provider"> <ref bean ="pr'/ >

</property > </bean>

</beans>

Q) How to implement constructor injection in a spring container? Ans: Step 1: I n spring bean class declare dependency variable. Step 2: Define constructor which will take that variable as parameter. Step 3: Use <constructor-arg> tag in bean configuration file &supply the value.

Example for constructor iniection where de~endencv is ~rimitive t v ~ e : public class Purse{

private double money; public Purse(double money){

this.money=money; 1

1

Spring configuration file: cbeans ... >

<bean id="purseU class="Purse"> cconstructor-arg value="lO"></ constructor-arg>

(or) <constructor-arg value="lOt'/>

(or) < constructor-arg >

< value>lO</value> c/constructor-arg >

</bean > </beans>

Exam~le for Constructor iniection where de~endencv is obiect tvpe: public class Provider { 1

public class Customer{ private Provider provider; public Customer(Provider provider){

Naresh i ~echnolo~ies, Opp. Satyam Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842 a

An IS0 9001 : 2000 Certified Company - - - -- --

Page 7 http://javabynataraj.blogspot.com

Page 37: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- -

By Mr. ~ o m a s e k h a r ~ e d d y [ ~ e r t i f i e d ~rofessional)

this. provider= provider;

Spring configuration file: <beans ... >

<bean id="providerRef" class= "Providerf'/> <bean id="cuctomerRef" class="Customer"~

cconstructor-arg ref="providerRef> </constructor-arg> (or)

cconstructor-arg ref="providerRef/> (or)

cconstructor-arg > <ref bean= "providerRef"/>

c/constructor-arg> </bean>

</beans>

I -" -. - -

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

1 An I S 0 9001 : 2000 Certified Company

Page 8 http://javabynataraj.blogspot.com

Page 38: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

By Mr. SomasekharReddylCertified Professional? ''

Bean alias name can be used to define multiple names for a configured spring bean. We can define alias - names with "name" attribute of <bean> tag.

- . 2 r .

-- S r B ~ a n A l i a s P r-~jetct 1 ~9 51.c - 1

i z g& JEE Syrt~m Library [!13 x:.l;.k 1.61 ;.. Spring 2.5 Ccarc Libraries

.* t-

GreetinaBeamiava 1. package com.neo.spring.beans; 2. public class GreetingBeant 3. private String name; 4. 5 . public void semame (String name) {

6. this.name=name; 7. 1 8. 9. publicStringgetName0 {

10. return name; 11. 1 12. 1

a~~licationContext.xml 1 . <?xml version= "1.0 " encoding= "UTF-8"?> 2. <beans 3 . xmlns= "h t tp : //www. springframework. org/schema/beans " 4 . xmlns :xsi= "http://www. w3. org/2001/~~~Schema-instance" 5 . xmlns : p= "h t tp : //www . springframework. org/schema/p " 6 . xsi : schemaloca tion= "h t tp : //www. springframework. org/schema/beans

7 . h t tp : //www. springframework. org/schema/beans/spring-beans-2. 5. xsd "> I 8 - 9 . <!- - here we can write bean alias using name attribute - - > 10. <bean id= "gb" name= "gbl , gb2, gb3, gb4 " 11. class="com.neo.spring.beans.GreetingBean"> 12. <property name="nameW value="welcome to NIT" property> 13. </bean> 14. </beans>

GreetinaTesLiava 1. package com.neo.spring.beantest; 2. import org.springframework.context.App1icationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext;

I-- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I . -

An IS0 9001 : 2000 Certified Company Page 1

http://javabynataraj.blogspot.com

Page 39: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Bv Mr. SomasekharReddvfCertified ~ r o f e s s i o n a l r

4. import com.neo.spring.beans.GreetingBean; 5 . public class GreetingTest {

6. 7. private static Applicationcontext context = new 8. ClassPathXmlApplicationContext(~~applicationContext.ml~); 9. public static void main(String[] args) {

10. 11. GreetingBean greetingBean = (GreetingBean) context . getBean ( "gb") ; 12. String narne=greetingBean . gewame ( ) ; 13. System. out .println (name) ; 14. String aliasNames I:] = context. getAliases (I8gbv1) ;

15. System. out .println ("The following are Alias names of gb : If) ; 16. for (int i = 0; i < aliasNames.length; i++) {

17. System. out .println (aliasNames [i] ) ; 18. 1 19. 1 20. 1

Outuut welcome to NIT The following are Alias names of gb: 9b2 9bl 9b3 gb4

1 % name= f fqbl , qb2, qb3, qb4 class= "corn. neo. spring.beans. GreetingBean If>

we can also write like above in configuration file without id attribute,here the container creates object based on given alias name. ex : -

GreetingBean greetingBean = (GreetingBean) context . getBean (llgbllf) ;

1 Here the container treats ' gb l ' as unique id reference, remaining references as alias to that unique id

I f we mint alias names now then the o u t ~ u t is: String aliasNames [I = context . getAliases (Irgblv1) ;

System. out .println (llNow the Alias names will be as follows : 11) ; for (int i = 0; i < aliasNames.1ength; i++) {

System. out .println (aliasNames [i] ) ;

O U ~ D U ~ welcome to KIT Now the Alias names will be as follows: gb2 gb3 gb4

So here the 'gbl ' treated as unique id references, remaining as aliases

) Kev notes on id, name attributes :

- - - --

Naresh i Technologies, Opp. Satyam f heatce, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- An IS0 9001 : 2000 Certified Company - - - -- - . -

Page 2 http://javabynataraj.blogspot.com

Page 40: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

By Mr. SomaseltharReddy(Certified Professional;?' I 1

9 I d attribute is used t o define reference of configured spring bean. 9 id value should be unique, whereas name no need to be uniqure. ,. . 9 I d value won't allow special characters (like /, -,*... etc). whereas name attribute allows any kind

of special characters. , ,

> The name attribute is useful when we develop spring MVC based web applications, because As we know every URL should start with "/". ..

9 Generally most of the cases we use id attribute only but not name attribute.

Sinsleton - I

Generally we create singleton when there is no instance variables and static variables t o save the memory.

Mvsingleton

; i @..-@ corn,r~eo, :;ir~gleton, customer . . Q.. Car,jwa . . . . . .

@i & IRE System Library [JAVA] +.

Car.iava 1. package com.neo.singleton.customer; 2. public class car {

3. private static Car car=new Car () ;

4 . private Car ( ) {

5. System. out. println ("Car ( ) copstructorff) ; 6. 1 7. public static Car getInstance () {

8. return car; 9. 1 10. 1

Test.iava 1. package com.neo.singleton.test; 2. import com.neo.singleton.customer.Car; 3. public class Test {

4. public static void main (String[] args) {

5. Car carl=Car.getInstance(); 6. Car car2=Car.getInstance(); 7 . Car car3=Car.getInstance(); 8 . Car carl=car. getInstance ( ) ;

9. Car car5=Car. getInstance () ;

10. Car car6=Car. getInstance () ;

11. System. out .println(carl) ; 12. System. out. println (car2) ; 13. System. out. println (car3) ; 14. System. out .println (car4) ; 15. System. out . println (car5) ; 16. System. out .println(car6) ;

- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I

- An IS0 9001 : 2000 Certified Company I Page 3

http://javabynataraj.blogspot.com

Page 41: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- - - - - . - -

TSpring-lOc --. .- - .- . . . . - - . - - -. . -- .. -. By Mr. -- SomasekharReddy(Certified - -- - -- Professional) - -

output Car ( ) constructor com.neo.singleton.customer.Car@36ObeO ,

com.neo.~ingleton.~~~tomer.Car@36ObeO com.neo.singleton.customer.Car@36ObeO com.neo.singleton.customer.Car@36ObeO com.neo.singleton.customer.Car@36ObeO corn.neo.singleton.customer.Car@36ObeO

3 So this is the way to create singleton object. But here we are implementing our own logic to implement singleton.

3 I n the case of spring singleton design pattern is implicitly implemented. To make one object as singleton, or non-singleton just we need change confiuration in the spring configuration file. But we no need to implement our own logic.

sprina scopes $3, ,@ scopeproject

i f&. L% src s . .

: i @,-= com.neo .spring.bean . , . . . ' i &... pJ SpringEean,java ; : < j ; f$J . ~ $ ! ;

j j c+& @ Client, jaua , . . . , ! : ' I i......'S .. , 3.- applicationContext .xml I 13 .-a JRE System Lit1rat-y [,3-;':r:j;5,L-,E--- 1 ,el

[&-.& Spring 2.5 Core Libraries

This is just an empty bean our aim is to find out how the container is creating objects when we try t o call this bean. Let's see this by the examples.

SprinclBean.iava 1. package com.neo.spring.bean; 2. public class SpringBean {

3. 4. 1

a~ulicationCantext.xmI(configuration file)

without any attribute declarations in the <bean> tag.

Here we are testing the application. Client.iava

-. -- Naresh i Technologies, Opp. Satyam s heat re, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

-. - - - - . . -- . - -

An IS0 9001 : 2000 Certified Company . .

p a g e 4 http://javabynataraj.blogspot.com

Page 42: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

. -- ...-. - -..-......

I Sering-IOC By Mr. ~ o m a s e k h a r ~ e d d v f ~ e r t i f i e d professional‘^^ --l

1 . package com . neo . spring. client; 2. import org.springframework.context.App1icationContext; 3. import o r g . s p r i n g f r a m e w o r k . c o n t e x t . s u p p o r t . C l a s s P a t ~ p p l i c a t i o n C o n t e x t ; 4. import com.neo.spring.bean.SpringBean; 5. public class Client{ 6. private static Applicationcontext context = new 7. ClassPathXmlApplicationContext( 8. "/~om/neo/somashekar/spring/config/application~ontext.~l~~); 9. 10. public static void main (String[] args) {

11. SpringBean springBean1 = (SpringBean) 12. context. getBean ("sb") ; 13. Systern.o~t.println(~~object I-->" + springBean1); 14. SpringBean springBean2= (SpringBean) c~ntext.getBean(~~sb"); 15. Sy~tem.out.println(~~object 2-->" + springBean2); 16. SpringBean springBean 3= (SpringBean) 17. context. getBean ("sbl') ; 18. System.out.println(~object 3-->" + springBean3); 19. 1 20. 1

Output object I--> com.neo.spring.bean.SpringBean @ld7fbfb object 2--> com.neo.spring.bean.SpringBean@ld7fbfb object 3--> com.neo.spring.bean.SpringBean @ld7fbfb

Analvsis By observing the above application the spring container creates only one object (returning same address) even we call getBean("objRef") 'n' no. of times. So by default a spring bean is "SingleTon".

4 I f we want to change its nature to "Non-SingleTon" i.e. for each 'getBean ()'method call on container one brand new instance has to be created. To achieve this we can make use of "scope" attribute of <bean> tag.

9 Scope attribute takes two values: 1) singleton 2) prototype

Let's see this by our application by rewriting configuration file i.e. applicationContext.xml file

a~~licationContext.xml 1. <?xml version="l. 0" encoding="UTF-8"?> 2. <beans xmlns="http://www.springframework.org/schema/beansr1 3. xmlns:xsi="http://www.w3.org/200l/XMLSchema-instancew 4 . xsi:schemaLocation="http://www.springframework.org/schema/beans 5. http://www.springframework.org/schema/beans/spring-beans-2.O.xsd11> 6. <bean id="sbW class=1r com.neo.spring.bean.SpringBean " 7 . ~cope=~singleton"> 8. </bean> 9 . </beans> Now run the Client.java again, then we will get output something like this shown below

Output object I--> com.neo.spring.bean.SpringBean@ld7fbfb object 2--> com.neo.spring.bean.SpringBean@ld7fbfb j I objezt 3--> com.neo.spring.bean.SprinqBean@ld7fbfb I

Analvsis ! 1

........................ - . Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1

An IS0 9001 : 2000 Certified Company . -- ...............

P- J

http://javabynataraj.blogspot.com

Page 43: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

.-. .. ........... - - -. .- , --- Spring-IOC . ........ ............... By Mr. ~ o m a s e k h a r ~ e d d ~ ( ~ e r t i f i e d

1 Even with or without declaring the scope attribute we are getting the same output. So by default the spring bean is singleton. Now if we want the same spring bean non-singleton we can make use of scope attribute value i.e. prototype. e Let's rewrite the application and observe the output by using the scope attribute value in

configuration file.

Now run the Client-java again, then we will get output something like this shown below

1 1 --> corn. neo. apring.bean . SpringBeane le57e8f

Analvsis In the above output the spring container has created three different objects i.e. we made spring bean as Non-SinsleTon by making use of 'scope=prototypel.

-

Mote: I n old versions of spring we used t o use "singleton" attribute of <bean> tag explicitly to achieve single ton and non-singleton nature.

object 2--> com.neo.spring.bean.SpringBean@ld7fbfb object 3--> corn.neo.spring.bean.SpringBean@e020~9

All ~ a s s : S j a. s:l>gleton e Sl.~ecifies to container to create the configured spring bean only once in the container. b. prototype e Si3ecifies the container to create the configured spring bean for each time when it is requested

(cJetBean("springref")). c. request Q Specifies the container to create the configured spring bean once in per web request. It is

applicable only in web module. d. s~ssion

5 ecifies the container to create the configured spring bean once per HttpSession. It is applicable ci IIY web module.

e. 9 obalsession s,,ecifies the container to crate the configured spring bean once in a global session. It is applicable i r , portals.

f. t,,iead Q S, ecifies the container to create the configured spring bean once per each thread. It is not

ii ~~p l ic i t l y registered. I f we want t o specify thread as a scope for bean, we have t o register e ~pl~citly.

-3.x. 7,9' ..........-. - idaresh i Technologies, Opp. Satyarn Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842 1

An IS0 9001 : 2000 Certified Company .- .............

Page 6 http://javabynataraj.blogspot.com

Page 44: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Constructor Ambiquitv

- $ ccum,neo,arnhiguity ,r_lient + I J _ _ Client ,lava

I I 'r L 3RE System Library [JAVA] @& r : / . ; Jpllng 2.5 Core Libraries 1

Em~lovee~iava 1. package com.neo.ambiguity.customer; 2. 3. public class Employee {

4. private ~ n t eno=l; 5. private String name=null; 6. privatedouble sal=O.O; 7. private String desig="clerkw; 8. public Employee (int eno, String name) {

9. th~s.eno=eno; lo. this.name=name; 11. 1 12. public Employee(doub1e sa1,String desig) {

13. thls.sal=sal; 14. this. desig=desig; 15. 1 16. 17. public v o ~ d getEmployeeDetails(){ 18. System. out. println (eno) ; 19. System. out. println (name) ; 20. System. out .println (sal) ; 21. System. out. println (desig) ; 22. 1 23. }

Client.iava 1 . package com . neo . ambiguity . client; I 3. import org.springframework.context.App1icationContext; 4. import org . spr ingframework.context . support .ClassPa~pl ica t ionContext ; I 5. import com.neo.ambiguity.customer.Employee; 6. 1 - 7. public class Client {

8 . private statlc Appli cationcontext contexenew I 9. ClassPathXmlApplicationContext ( lrapplicationContext . xml ) ;

10. public static void main (String[] args) {

11. Employee employee = (Employee) context. getBean ("empref 'I) ; I 12. employee. getEmployeeDetails ( ) ;

13. 1 I 14. )

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 I -- --

An IS0 9001 : 2000 Certified Company -. - - -- - - - -

Page 1 http://javabynataraj.blogspot.com

Page 45: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- -- -- . . - -

I SprinnIOC Bv Mr. SomasekharReddvlCertified Professional] 1

I a~~licationContext.xrnI 1 . < ? m l version="l .0 I' en~oding="UTF-8~~?>

1 : : <bez;ns=llhttp : //www . springf ramework . org/schema/beans It 4 . xmlns:xsi=t'http://www.w3.org/2OO1/~~Schema-instancet1 1 5. xsi:schemaLocatron=tthttp://www.springframework.org/schema/beans 6. http://www.~prrngframework.org/schema/beans/s~rin~-beans-2.5.xsd~~>

I : <bean rd='lempref 'I cla~s=~~com. neo . ambiguity. customer. 9. <constructor-arg ~ a l u e = ~ ~ 1 0 0 1 ~ ~ X/constructor-arg> 1 10. <constructor-arg value=I1sekharn ~/ccnstructor-arg> 11. </bean> 1 12, </beans>

1 I n the above program, we can't expect the output. Because Employee class having two constructors wi th two arguments and it takes the value in String and i t converts into corresponding type. So it may assign to Employee(eno,ename) or Employee(sal,desig).

output 1 . .

1 0 0 1 . 0 I s e k h a r

7 Here, it assign to Employee(sal,desig). To avoid this ambiguity problem. I t has two attributes.

1.) index + it specifies the index of the argument (i t takes from '0'). 1 2.) type + it specifies the type of the argument. For object type we have to give fully qualified name. For primitives directly we can give the corresponding privitive key words.

I Now modify 'applicationContext.xml" to avoid the ambiguity problem as follows.

a~~licationContext.xml 1. <beans 2. xmlns=lhttp: //www . springframework. org/schema/beanstl 3. xmlns:xsi="http://www.w3.org/2OO1/XMLSchema-instancett 4 . xsi:schemaLocation=tthttp://www.springfraework.org/schema/beans 5. http://www.springframework.org/schema/beans/spring-beans-2.5.xsdtt> 6. <bean id="empreftl class="com.neo.ambiguity.customer.Employeelt> 7 . <cons tructor-arg ~alue=~~1001 l1 i n d e ~ = ~ ~ O ~ l type=ttinttt / . 8. <constructor-arg value="sekhartt index=Itl It type=I1 java. lang. String" /> 9. </bean> 10. </beans>

O U ~ D U ~ 1 0 01 se k h a r 0 . o c l e r k

1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

i- - - -- - - -- -- -- An I S 0 9001 : 2000 Certified Company

Page 2 http://javabynataraj.blogspot.com

Page 46: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Spring-IOC By Mr. SomasekharReddy(Certified Professional) '

, -, Q) Describe the different types of containers in spring framework? Ans: Spring containers are of 2 types.

1) Bean Factory based. -,

2) Applicationcontext based. ' ,

Bean Factorv based BeanFactory is an interface .it's implementation class is XmlBeanFactory. ,

XmIBeanFactory

e Create instance of XmlBeanFactory class , is nothing but we create spring container. d Constructor o f XmlBeanFactory class takes Resource object as argument, which represents

,

spring configuration file. d There are two implementation classes of Resource interface, which are used to specify spring 7

configuration file.

Usins XmlBeanFactorv with FileSvstemResource container 1. package com.neo.spring.client; 2. import org.springframework.beans.factory.BeanFactory; 3. import org.springframework.beans.factory.xm1.XmlBeanFactory; 4. import org.springframework.core.io.Fi1eSystemResource; 5. public class Client {

6. private static BeanFactory beanFactory = new XmlBeanFactory( /

7 . new FileSystem~esource(~~~:/SomasekharReddy/Struts/workspace \

8 . /springcontainer/src/app~icationContext.xm~ll)); 9.

-

10. public static void main(String[] args) {

11. System. out .println (beanFactory . getBean ('eft') ) ;

12. 13. 1 14. 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 /

. - .- An IS0 9001 : 2000 Certified Company

--

Page 1 http://javabynataraj.blogspot.com

Page 47: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

By Mr. Somasel<harReddy[Certified Professional)

I n the above example FileSystemResource is taking complete system path(abso1ute path). So in the 1 future if we change location of the project then again we need to change the location of spring

configuration file in the program. That's why i t is not advisable to use FileSystemResource.

Usins XmlBeanFactorv with ClassPathResource container 1. package com.neo.spring.client; 2. import org.springframework.beans.factory.BeanF%ctory; . 3. import o r g . s p r i n g f r a m e w o r k . b e a n s . f a c t o r y . x m 1 . ~ ; 4. import org.springframework.core.io.ClassPathResource; 5. 6. public class Client {

7. private static BeanFactory beanFactory = new XmlBeanFactory(new 8. ClassPathResource(llapplicationContext.xml")); 9. public static void main (String[] args) {

10. System. out. println (beanFactory. getBean ('IspringBeaflef 11) ) ; 11. 12. 1 13. }

I n the above example container reading the configuration file from class path, but we are not specifying the complete path. Even we change the location of the project in the system, still our application work without modification. Because i t reads configuration file from classpath. So i t is advisable to use ClassPathResource instead of FileSystemResource.

- Key notes on BeanFactory based containers 0 It is a light weight container. Q It loads spring beans configured in spring configuration file, and mknages the life cycle o f t he

I I spring bean when we call getBean("springbeanrefU). So when we call getBean("springbeanrefV)

then only spring bean life cycle starts.

I 0 Generally it is used t o develop stand alone applications, mobile applications.

A~~l icat ionContext based / It is a child interface of BeanFactory. 7 - - - - - - -

1 I BeanFactory 1

I I

Usinq FileSvstemXmlA~~licationContext I 1 . package corn. neo . spring. client; 2.

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L - - - - - - - - - -- An I S 0 9001 : 2000 Certified Company

Page 2 http://javabynataraj.blogspot.com

Page 48: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- - -- -- - -

~ ~ E - I O C By Mr. SomasekharReddy[Certified Professional] '

I 3 . import org. sprlngframework. context .ApplicatronContext; I

4. import org.spr~ngframework.context.support.FileSystemXmlAppl~cat~onContext;

5. 6. public class Client {

7. private static ApplicatlonContext context = new FileSystemXmlApplicationContext( 8. 11~:/~omasekhar~eddy/~truts/workspace/springcontalner/src/appl~cation~ontext.xml");

9. - 10. publlc statlc vold main (String[] args) {

11. System. out. prlntln (context. getBean ('IsprlngBeanRef If) ) ; 12.

I 13. 1 14. 1 1

I f we use F~leSystemXrnlApplicationContext container, we need to pass absolute path of the spring I configuration file to this constructor. So, if the project location is changes we need to change the our application. So it is not advisable to use this container. I Usincl ClassPathXmlA~~licationContext 1. package com.neo.spring.client; 2. 3. import org.springframework.context.ApplicationContext; 4. import org.springframework.context.support.ClassPathXmlApplicationContext; 5. 6. public class Client {

7. private static ApplicationContext context = new 8. ClassPathXmlApplicationContext (llapplicationContext. xml") ; 9. public static void main (String[] args) {

10. System. out. println (context. getBean ("springBeanRef") ) ; 11. 12. 1 13. )

14.

_I I n the above example container reading the configuration file from class path, but we are not

specifying the complete path (absolute path). Even we change the location of the project in the system, still our application work without modification. Because it reads configuration file from classpath. So it is advisable to use ClassPathXmlApplicationContext container. I Usincl XmlWebA~plicationContext This is used in sprinb webmvc module. This container object created by web container internally. We no I need to create on our own.

Key notes on ApplicationContext I It loads spring beans configured in spring configuration f~le, and mknages the life cycle of the spring bean as and when container starts, i t won't wait until getBean() method is called. I ApplicationContext based container provides all the features of BeanFactory. I n addition to them it provides the following features also. I

1) Event-handling support - 2) Internationalization support 3) Remoting 1 4) EJB Intigration 5) Scheduling 6) JhlDI look-up ... etc.

I I n enterprise level application always Applicationcontext based container is used. 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I -- - - - - . - - An IS0 9001 : 2000 Certified Company

Page 3 http://javabynataraj.blogspot.com

Page 49: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Spring-IOC By Mr. SomaseltharReddy[Certified Professional)

S ~ r i n q bean life-cvcle 1 Spring container controls the life cycle of spring bean i.e. from instantiation to destruction. Spring bean has 4 life cycle states: 1 P Instantiation

P Initialization 1 P Ready t o use (method ready t o use state) > Destruction

0 initial~zation method, destruction method can be given t o spring been in the following ways P By implementing spring framework given interfaces they are

1. InitializingBean 2. DisposableBean

P By configuring custom initialization and destruction method in the spring configuring f ~ l e using <bean> tag attributes

o ~nit-method o destroy-method

P By using annotations o PreDestroy o Postconstruct

Note: if spring bean is implementing framework interface 'InitializingBean", we need to define afterPropertiesSet() in bean class. It becomes the initialization method .Similarly if bean implements "DesposableBean" interface , destroy method becomes destruction method & no need t o inform.

Q) What is BeanNameAware and why it is used? Ans: BeanNameAware is an interface and it has one method i.e., setBeanName(String), by overriding this method we will get the name(configured name) of the bean. This is used t o know the configuration name of the s p r i ~ g bean.

I EX : public class SprlngBean implements BeanNameAware { I private String name ;

I public void setName (String name) { this.name = name;

1 I public void setBeanName(String beanName) { I System. o u t . println ( "beanName is : "+beanName) ; I 1 i 1

I Q) What is BeanFactoryAware? Ans: BeanFactoryAware is an interface. It is used to get the container information in which spring bean is available. 1 I t has one method i.e., setBeanFactory(BeanFactory). EX: public class SpringBean implements BeanFactoryAware {

private String name ; public void sewame (String name) {

I this .name = name;

- - 1

I public void setBeanFactory(BeanFactory factory) throws BeansException {

System. ou t .println (factory) ; 1

Q) What is ApplicationContextAware?

I I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L- - . . - -

An I S 0 9001 : 2000 Certified Company Page 1

http://javabynataraj.blogspot.com

Page 50: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - -- - --

Spring-IOC By Mr. ~ o m a s e k T ; a r ~ e d d ~ ( ~ e r t i f i e d ~rofessiona1)z I

I -,I

Ans: ApplicationContextAware is an interface, it is also contain one method i.e., 'I setApplicationContext(ApplicationContext). It is also used to get the container information in which / J spring bean is available.

I Ex: public class SpringBean implements ApplicationContextAware{

private String name; public void setName (String name) {

this.name = name; 1 public void setApplicationContext(ApplicationContext context)

throws BeansException {

System. out .println (context) ; 1

1

BeanPostProcessor: BeanPostProcessor is an interface. I t has two methods:

9 postProcessBeforeIntialization(Object, String) 9 postProcessAfterInitialization(Objed, String)

BeanPostPocessor is used to provide some common logic to all beans o r to set of beans which are - I configured in spring configuration file.

o postProcessBeforeIntialization() method is executed before the initialization method called. 1 1 o postProcessAfterInitialization() method is executed after the intialization method called. -

These methods will be called for each spring bean, which is configured in spring configuration file. : I Q) How to use BeanPostProcessor? Ans: We have to write some class and we have to implement BeanPostProcessor interface. And we 1 have to override the postProcessBeforeIntialization() and postProcessAfterInitialization() methods.

\ I I I

Then register user defined BeanPostProcessor object with spring container. i.e configure the user defined BeanPostProcessor bean in spring configuration file. ' I _ I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I An IS0 9001 : 2000 Certified Company

- . - -- . - - - - - - - 1 Page 2

http://javabynataraj.blogspot.com

Page 51: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

' Spring-IOC By Mr. ~ o m a s e k h a r ~ e d d ~ ( ~ e r t i f i e d Professional) .~ ..................................................... --

I

! ."

. . ,+: 1~ustornBear1PostPrc11:es5or, java

. . . ...., I ; . . fii,[a ~ ~ r i r l ~ ~ i a r l . java , . I .& com,neo,spring,client . . . . . , 1 i iEi Client. java

:

' ' * j $3 t~ corn .ne~>,spring,conFig I ; ,. , ",

... .. i.)~' ..., applicatiur~c:untext ,xrrll

S ~ r i n q Bean Life Cvcle

S~rinuBean. iava 1. package com.neo.spring.bean; 2. import javax.annotation.PostConstruct; 3. import javax.annotation.PreDestroy; 4. import org.springframework.beans.BeansException; 5. import org.spr~ngframework.beans.factory.Bean~; 6. import org.springframework.beans.factory.BeanFactoryAware; 7. import org.springframework.beans.factory.BeanNameAware; 8. import org.springframework.beans.factory.Disposab1eBean; 9. import org.springframework.beans.fa~tory.Initia1izingBean; 10. import org.springframework.context.App1icationContext; 11. import org.springframework.context.App1icationContextAware; 12. 13. public class SpringBean implements InitializingBean, DisposableBean, 14. BeanNameAware, BeanFactoryAware, ApplicationContextAware {

15. private String name; 16. 17. public SpringBean ( ) {

18. sop ( I' SpringBean ( ) 'I) ; 19. 1 20. 21. public void setName(String name) {

22. this.name = name; 23. sop (llSpringBean. seWame (String name) If) ;

24. 1 25. 26. publlc String geWame() {

27. / / Service method of SpringBean 28. sop("SpringBean is servicing now. this state is called 29. method ready state ") ;

1 30. return name; 31. 1

1 32. - - 33. @Override 1 3 4 . public void afterPropertiesSet() throws Exception {

35. sop ( "Ini tializingBean . af terPropertiesSet ( ) 'I) ; 36. 1 37. 1 38.

1 39. @Override

1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

-. - - -- -- -. - - . An IS0 9001 : 2000 Certified Company . - -. . -- -- - -

Page 3 http://javabynataraj.blogspot.com

Page 52: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Spring-IOC - - . ... . .. . . . . . .. . . . . . .... . . . . . . . . . .. . . . . .. . . . . . . - By Mr. SomasekharReddy(Certified -- -- - .. . . .

Professional) ::; M I

public void destroy() throws Exception {

sop ( "DisposableBean . destroy ( ) If) ;

public void configuratinIni.t() { sop i init-method. configuratinInit ( ) ") ;

1

public void configurationDestroy() {

sop ("destroy-method. configurationDestroy ( ) It) ;

1

@ Pos tconstruct public void annotationInit0 {

sop (wPostConstruct. annotationInit ( ) " ) ;

1

@ PreDes troy public void annotationDestroy () {

sop ( "PreDestroy . annotationDestroy ( ) I!) ;

1

/ / knowing spring bean name @Override public void setBeanName(String beanName) {

sop ( I1BeanNameAware. setBeanName (String beanName) : + beanName) ;

1

/ / where spring bean is residing @ Override public void setBeanFactory(BeanFact0ry factory) throws

BeansException {

sop (llBeanFactoryAware. setBeanFactory (BeanFactory factory) : + factory) ;

/ / where spring bean is residing @Override public void setApplicationContext(ApplicationContext context)

throws BeansException {

sop(~ApplicationContextA~are.setApplicationContext(ApplicationContext context) : + context) ;

public void sop(0bject object) {

System. out .println (object) ; 1

1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

I - -

- -- - - - -- . - Page 4

http://javabynataraj.blogspot.com

Page 53: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- . -. - -

- Spring-IOC By Mr. SomasekharReddy/Certified Professional]

CustomBeanPostProcessor.iava 1. package com.neo.spring.bean; 2. 3. import org.springframework.beans.BeansException; 4. import org.springframework.beans.fa~t~ry.~~nfig.Be~PostProcessor; 5. public class CustornBeanPostProcessor implements BeanPostProcessor {

6. 7. @Override 8. publlc Object postProcessBeforeInitial~zat~on(0bject beanObj, 9. String beanName) throws BeansException {

10. 11. System.out.println(~~CustomBeanP~stProcessor.postProcessBefore 12. Initialization(0bject beanObj, String beanName)I1); 13. System. out. println ("BeanOb ject is : 'I + beanObj ) ; 14. System. out .println ("Bean Name is : " + bearname) ; 15. 16. return beanObj ; 17. 1 18. 19, @Override 20. public Object postProcessAfterInitialization(Object beanObj, 21. String beanName) throws BeansException {

22. 23. System.out.println(t~cu~t~~eanPostProcessor.post~rocess~ter 24. Initialization(0bject beanObj, String beanName)I1); 25. System. out. println ("BeanObject is : + beanobj ) ; 26. System.o~t.println('~Bean Name is : " + bemame); 27. 28. return beanOb j ; 29. 1 30. 1

Client.iava 1. package com.neo.spring.client; 2. import org.springframework.context.support.AbstractApp1icationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 4. 5. import com.neo.spring.bean.SpringBean; 6. 7. public class Client {

8. 9. private static AbstractApplicationContext context = new lo. C l a s s P a ~ p p l i c a t i o n C o n t e x t ( 11. ~~com/neo/spring/config/applicationContext.xmlv~) ;

12. 13. public static void main(String[] args) {

14. 15. SpringBean bean = (SpringBean)context.getBean( 16. "springBeanRef ") ; 17. String name = bean. getName ( ) ; 18. System. out. println ("Injected value is : "+name) ; 19. context. close ( ) ;

20. 1 21. 1

I I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- I An I S 0 9001 : 2000 Certified Company - . -- -- - -

Page 5 http://javabynataraj.blogspot.com

Page 54: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

a~plicationContext.xml 1. <? xml version="l .0" encoding="UTF-8"?> 2. <beans xmlns="http://www.springframework.org/schema/beans~~ 3. xmlns : xsi="http: //www. w3. org/2001/~~~Schema-instance" 4 . xmlns:context="http://www.springframework.org/schema/context~~ 5. xsi:schemaLocation="http://www.springframework.org/schema/beans 6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 7. http://www.springframework.org/schema/context 8. http://www.springframework.org/schema/context/spring-context-2.5.xsd~~> 9. 10. <context:annotation-config /> 11. <bean name="springBeanRefn class=~'com.neo.spring.bean.SpringBean" 12. ~n~t-rneth~d=~!configuratinInit" destroy-method=" 13. configurationDes troy1!> 14. <property name= "name I!>

15. <value>lifecyclebean</value> 16. </property> 17. </bean> 18. 19. <bean class="com.neo.spring.bean.CustomBeanPostProcessor~~~/bean> 20. 21. </beans>

O U ~ D U ~ SpringBean ( ) SpringBean. setName (String name) BeanNameAware.setBeanName(String beanName) : springBeanRef BeanFactoryAware.setBeanFactory(BeanFactory factory) : org.springframework.beans.factory.support.DefaultListableBeanFactory@47612B: defining beans [org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframe work.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context. annotation.internalRequire~notationProcessor,springBeanRef,com.neo.spring.bean.CustomBe anPostProcessor#0]; root of factory hierarchy ApplicationContextAware.setApplicationContext(ApplicationContext context) : org.springframework.context.support.ClassPathXmlApplicationContext@19aOc7c: display name [org.springframework.context.support.ClassPathlApplicationContext@l9aOc7c]; startup date [Sun Feb 27 18:13:42 IST 20111; root of context hierarchy PostConstruct.annotationInit() CustomBeanPostProcessor.postProcessBeforeInitialization(Object beanObj, String beanName) BeanObject is : com.neo.spring.bean.SpringBean@e61a35 Bean Name is : springBeanRef InitializingBean.afterPropertiesSet() init-method.configuratinInit() CustomBeanPostProcessor.postProcessAfterInitialization(Object beanObj, String beanName) BeanObject is : com.neo.spring.bean.SpringBean@e61a35 Bean Name is : springBeanRef PreDestroy.annotationDestroy() DisposableBean.destroy() des troy-method . configurationDes troy ( )

/

Q.) How to give same init, destroy method for all the spring beans configured in spring configuration file? I

By configuring default-init, default-destroy attributes of c beans> tag , we can specify same init, ( destroy methods for all the spring beans configured in spring configuration file.

Q cbean xmIns="http ........." default-init-method="x" default-destroy-method=" y"/> I f'

Naresh i ~ e c h n z ~ i e s , Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 An IS0 9001 : 2000 Certified Company I

- - -- - .- - - -- - . -- - - -

Page 6 http://javabynataraj.blogspot.com

Page 55: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - - - . . . -. --

Spring-IOC By Mr. Somasekl~arReddy(CertiFied Professional]

Inheritance 1 We have two types of inheritances. 9 Bean level inheritance

l o Configuring child bean, with its own properties as well as wi th parent properties. 9 Bean Configuration level inheritance

i o Re~s ing bean configuration in other bean configuration

. . : r&.f:a sri

I <,a &,,'

I : i T-B : :sr!. conl,neo, spring, hear1

:+'! . $ ~ ~ j i l l j , ~ ~ ~ . ~ ~ . . ?-. I ; . ;

. . . $j Parej-it. java , ' ,

, t

I 7 "

,zl a corn, neo,spring.config , , . . . .

. ,..I<

, . , . ...... I,. a. . . < ,

p* applicationContext ,xml

j . i$2- . @+, JRE System Library [JRE] j &i Spring 2.5 Core Libraries

Bean level inheritance

Child.iava 1. package com.neo.spring.bean; 2. public class Child extends Parent {

3. private String barnabbits ; 4. private String knowledge; 5. public void setBadHabbits (String badiabbits) {

6. thls.badHabbits = barnabbits; 7. 1 8. public void setKnowledge(String knowledge) {

9. this.knowledge = knowledge; 10. 1 11. public void displayDetails() {

12. System. out .println (getMoney ( ) ) ;

13. System.out.println(getPropDocs()) ; 14. System.out.println(getDiseases()); 15. System. out .println (badlabbits) ; 16. System.out.println(know1edge); 17. 1 18. )

Parent.iava 1 1. package com . neo . spring. bean; 2. public class Parent { 1 3. private double money;

- - 4 . private Strlng propDocs; 5. private String diseases ; 1 6. public void setMoney(doub1e money) {

7. this.money = money; I 8 . 1 9. public void setPropDocs (String propDocs) { 1 10. this.propDocs = propDocs; 11. 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I - - -. . - An IS0 9001 : 2000 Certified Company

Page 1 http://javabynataraj.blogspot.com

Page 56: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

7- -- - -

! Spring-IOC By Mr. SomasekharReddy(Certified Professional) _I i 1

public void setDiseases(String diseases) {

this.diseases = diseases;

1 public double getMoney ( ) {

return money; 1 public String getPropDocs() {

return propDocs ; 1 public String getDiseases ( ) {

return diseases; 1

a~plicationContext.xmI 1. <?ml version="l.O" encoding=WTF-EW?> 2. <beans 3. xmlns="http://www.springframework.org/schema/beans" 4 . mlns:xsi="http://www.w3.org/2OO1/XML~chema-instance~~ 5. xsi:schemaLocat~on=~~http://www.springfrework.org/schema/beans 6. http://www.springframe~ork.0rg/~~hema/beans/spring-beans-2.5.xsd~~> 7. 8. <bean id="chlldW class=~'com.neo.spring.bean.Child~~> 9. <!-Here we are configuring parent properties in the 10. Child class configuration --> 11. 12. <property name="money" ~alue=~100~~/> 13. <property name=~~propDocs ~alue=l~debtdocs'~/> 14. <property name='ldiseasesll value="nodiseases"/> 15. 16. <property name="badHabbits" value="~moking~~/> 17. <property na.me=wknowledge~~ value="null"/> 18. </bean> 19. </beans>

Client.iava 1. package com.neo.spring.client; 2. import org.springframework.context.support.AbstractApp1icationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext;

Output 100.0 deb tdocs nodiseases

I

I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 An IS0 9001 : 2000 Certified Company -- - - - -- - - . - - - - - - - .-

Page rJ

4. import com.neo.spring.bean.Chi1d; 5. public class Client {

6. private static AbstractApplicationContext contexbnew 7. ~lass~ath)[m~plication~ontext("com/neo/spring/config/ 8. applicationcontext. xml ") ; 9. public static void main (String[] args) {

10. Child child= (Child) context. getBean (frchildvr) ;

11. child. displayDetails () ;

12. 1 13. )

http://javabynataraj.blogspot.com

Page 57: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

By Mr. SomasekharReddy[Certified Professional)

smoking 1 n u l l

I Bean Confiauration level inheritance ' a,.:&$ confiquratiunlevelir~heritar~~:e , ' a,..@ src . . / 1 : ,L ,*.3",

: . i - ! , ,+t . ~,'., ,: corn, nelzl, spring, bean , . .

: : l r . . . . . I""" . . . . i &: a Ewhoye, java

. . , . , . . corn, riels ,spring ,client > . , . . .

I i : ;+i .. [Jj (-lie I . _I. - ent, java

, . . : @.-,e9 IRE System Library [IRE]

W &A Spring 2,s Core Lihrarie.; t-

Em~lovee.iava 1. package com.neo.spring.bean; 2. publ ic c l a s s Employee {

3. pr iva te i n t eno ; 4. pr iva te S t r ing ename; 5. pr ivate double s a l ; 6. pr iva te St r ing des ig ; 7. pr iva te St r ing hno; 8. pr iva te St r ing c i t y ; 9. publ ic void setEno ( i n t eno) {

10. th is .eno = eno; 11. 1 12. publ ic void setEname(String ename) 13. this.ename = ename; 14. 1 15. publ lc void setSal(doub1e s a l ) {

16. t h l s . s a l = s a l ; 17. 1 18. publ ic void setDesig (Str ing desig) 19. t h i s .des ig = desig; 20. 1 21. publ ic void setHno (St r ing hno) {

22. th is .hno = hno; 23. 1 24. publ ic void se tCi ty(Str ing c i t y ) {

25. t h i s - c i t y = c i t y ; 26. 1 27. publ ic void displayEmpDet.ails() {

28. System. out. p r i n t l n (eno) ; 29. System. out . p r i n t l n (ename) ; 30. System. out . p r i n t l n (sal) ; 31. System. out . p r i n t l n (desig) ; 32. System. out . p r i n t l n (hno) ; 33. System. o u t . p r i n t l n ( c i t y ) ;

34. 1 35. 1

I Naresh i ~echno lo~ ies , Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

. - _ _ _ _ _. An IS0 9001 : 2000 Certified Company

- -- - - - - -- Page 3

http://javabynataraj.blogspot.com

Page 58: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

By Mr. SomasekharReddy[Certified ~rofessional] '

Client.iava 1. package com.neo.spring.client; 2. import org.springframework.context.support.AbstractApp1icationContext; 3. import org.springframework.context.support.ClassPathXmlFpplicationContext; 4. import com.neo.spring.bean.Emp10yee; 5. public class Client {

6. private static AbstractApplicationContext context=new 7. ClassPathXmlApplicationContext( 8. 11com/neo/spring/config/application~ontext.xml11); 9. public static void main (String[] args) {

10. Employee employeel= (Employee) context. getBean ("empl") ; 11. employeel.displayEmpDetails(); 12. System. out .println() ; 13. 14. Employee employee2= (Employee) context. getBean (11emp2 'I) ; 15. employee2.displayEmpDetails(); 16. System. out .println ( ) ;

17. 18. Employee employee3= (Employee) context. getBean (11emp311) ;

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 -

An IS0 9001 : 2000 Certified Company - - -. . - - -

Page 4 -' http://javabynataraj.blogspot.com

Page 59: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

pp~

Spring-IOC By Mr. SomasekharReddy(Certified Professional) I . i

I out~ut. 1001 1 sekhar 2500.0 1 teammember 1-52-A

I Gunipalli 1002 somu

I 2500.0 teammember 1 1-52-B Gunipalli

1 1003 somasekhar 1 2500.0

-_ teammember 1-52-B i Gunipalli

Note: I n the above bean configuration all the three employees having same city name, same salary, same designation. So why don't we reuse the bean configuration.

e To reuse the bean configuration <bean> tag has parent attribute. Now we will rewrite the bean configuration file by using e m p l bean configuration to emp2, emp3.

a~ulicationContext.xmI 1. <?ml version="l.O" en~oding=~UTF-8"?> 2. <beans 3. xmlns="http://www.springframework.org/schema/beansrr 4. xmlns:xsi=~http://www.w3.org/2OOl/XMLSchema-instance~ 5. xsi:schemaLocation=f~http://www.springfrework.org/schema/beans 6 . http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 7. 8. <bean id="emplH class=~com.neo.spring.bean.Employee~~> 9. <property name="enoW value="1001"/> 10. <property name="enameW value=lfsekharff/> 11. <property name="salw ~alue=~2500"/> 12. <property name="desigfr ~alue=~teammember"/> 13. <property name="hno If value="l-52-Aft/> 14. <property name="cityn value="Gunipallin/> 15. </bean> 16. 17. <bean id=ffemp2" class=wcom.neo.spring.bean.Employee~ 18. parent="empl If> 19. <property name="enoqf ~alue=~1002"/> 20. <property name="enameW ~alue=~somu"/> 21. <property name="hno " value="l-52 -B"/> 22. </bean> 23. 24. <bean id="emp3" class=~corn.neo.spring.bean.Emp1oyeerf

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I- An IS0 9001 : 2000 Certified Company --

Page 5 http://javabynataraj.blogspot.com

Page 60: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- .- - .--

Spring-IOC 3

-- . nt r *.i *L .&1&

By Mr. ~ o m a s e k h a r ~ e d d ~ ( ~ e r t i f i e d Professional) -

-. 25. parent="empl "> 26. <property name="enon ~alue="1003~/> 1 27. <property name="ename" ~alue=~somasekhar~/> 28. <property name="hnoq1 val~e=~1-52-BI~/> 29. </bean> I ', 30. </beans>

. ,

Now run the Cl~ent~java, we w ~ l l get the same output.

sekhar 2500.0 teammember 1-52-A Gunipalli

1002 s omu 2500.0 teammember 1-52-B Gunipalli

1003 somasekhar 2500.0 teammember 1-52-B Gunipalli

* This is the way of reusing bean configuration.

Q.) What happens if both parent, child configuration has same property? I I

Ans: child property overrides parent property. i

'abstract' attribute 1 Generally in the bean configuration level inheritance, we will define one abstract bean configuration, which contains common properties, so that all the specific bean configurations can , extend that abstract bean. But no one should access that abstract bean configuration. For that

I purpose we use abstract attribute of <bean> tag. I

d Now we rewrite the above spring configuration file by make use of abstract attribute. I a~~licationContext.xmI 1 . < ? m l version="l .Oll en~oding=~IUTF-8~?> 2. <beans 3. xmlns=nhttp://www.spring£ramework.org/schema/beans11 4 . xmlns:xsi=~http://www.w3.org/2OO1/XMLSchema-instance11 5 . xsi:schemaLocation="http://www.springfraa/beans 6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd11> 7. 8. <bean id=ttabstractemp" class="com.neo.spring.bean.Employeell 1- 9. abs tra~t=~ltrue~~ > 10. <property name="sal It ~alue=~~2500 "X/property> 11. <property name=ltdesigv val~e=~teammember~~/property> 12. <property name=ltcityw value=~Gunipal l i~~ /property> 13. </bean>

- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- - - - - . - - - - . - - . An IS0 9001 : 2000 Certified Company Page 6

http://javabynataraj.blogspot.com

Page 61: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- - -

Spring-IOC By Mr. SomasekharReddy(Certified Professional) --

I i I

<bean 1d="emp3~~ ~lass='~com. neo . spring. bean. Employee" parent=llabstractempll>

<property name="en~~~ ~ a l u e = ~ ~ 1 0 0 3 ~ X / p r o p e r t y > <property name=llenamen ~alue=~somasekhar"~/property> <property name="hnoW ~ a l u e = ~ l - 5 2 - ~ ~ X / p r o p e r t y >

</bean> </beans>

- Client.iava ,

. 1 1. package com. neo . spring. client; 2. import org.springframework.context.support.AbstractApp1icationContext; 1 3. import org . springf ramework . context. support. ClassPathXmlApplicationContext; 4. import com.neo.spring.bean.Employee;

' 5. public class Client {

I 6. private static i%stractRpplicationContext context=new 7 . ClassPathXmlApplicationContext( 1 8. ~com/neo/spring/config/applicationContext.xml11); 9. public static void main(String[] args) { 1 10. Employee employeel= (Employee) context. getBean (llemplw) ;

11. employeel.displayEmpDetails(); 12. System. out .println() ; 1 13. 14. Employee employee2= (Employee) context. getBean (11emp2w) ; 1 15. employee2.displayEmpDetails(); 16. System. out. println () ;

I ::: Employee employee3= (Employee) context. getBean (11emp3") ; 19. employee3.displayEmpDetails(); 1 20. System. out .print111 ( ) ;

21. 1 22. / / Employee - - 23. employee= (Employee) context. getBean (llabstractempll) ;

1 z: / / employee.displayEmpDetails() ; 1

I sekhar

1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company - - -

PGe7-- !

http://javabynataraj.blogspot.com

Page 62: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- - .. - .. -

Spring-IOC By Mr. ~ o m a s e l t h a r ~ e d d ~ ( ~ e r t i f i e d Professional) - ,

i

2500.0 teammember 1-52-A. Gunipalli

1002 somu 2500.0 teammember 1-52-B Gunipalli

1003 somasekhar 2500.0 teammember 1-52-B Gunipalli

Exception in thread "main" orq.sprinqframework.beans.factory.Bean1sAbstractException: Error creating bean with name 'abstractemp': Bean definition is abstract

Note: 1f we will t r y to access abstract bean, we will get exception.

- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1

An IS0 9001 : 2000 Certified Company -. - -- - . -. - - -.

Page 8 http://javabynataraj.blogspot.com

Page 63: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - -

Spring-IOC By Mr. SomasekharReddy(Certified Professional) i --

Iniectins Collection obiects I 2 I f the dependencies are of type Arrays, List, Set, Map, properties ... etc, The way we inject the values for these dependencies are different from normal injection

1 > In general for some of the frame work given beans we need t o inject the Collection type objects.

1 Iniectins List obiect (where list contains primitive tvDes or Strinu objects)

I ., ,.....; applicatict7Scnt~~t,xml

I && JRE sy5ttm Libsall; i : . : i;':.:.; . + j

&A Sprinu 2,5 Col.e Libraries

1nistitueBean.iava 1. package com.neo.spring.bean; 2. import java.util.1terator; 3. import java.uti1.Lis.t; 4. 5 . public class InistltueBean {

6. private String name; 7. private List<String> facultyNames; 8 . private List<String> courseNames ;

9. 10. public void setName(String name) {

11. this. name = name ; 12. 1 13. 14. public void setFacultyNames(List<String> facultyNames) {

15. this.facultyNames = facultyNames; 16. 1 17. 18. public void setCourseNames(List<String> courseNames) {

19. this.courseNames = courseNames; 20. 1 21. 22. public void displayDetails () {

23. System. out .println ("Institue Name : " + name) ; 24. System. out. println (llFaculty Names are . . . 'I) ; 25. for (String facutlyName : facultyNames) {

26. System.out.println(facutlyName) ;

1 Double double1 = new Double(2500); System.out.println("Course names are . . . " ) ; Iterator<String> iterator = courseNames.iterator() ;

1 31. while (iterator.hasNext()) { 32. String courseName = iterator.next(); 1 33. System.out.println(courseName);

1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hydera bad, Ph: 040-23746666,23734842

- - . - - An IS0 9001 : 2000 Certified Company

Page 1 http://javabynataraj.blogspot.com

Page 64: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

a~plicationContext.xml I I

1. <?xml verslon="l. 0" en~oding="UTF-8~~?> - 1

2. <beans def a~lt-lnit-method=~ImyInit~~ default-destroy-method=r~myDe~tr~yrl ' 3. xmlns=1rhttp://www.springframework.org/schema/beans~t ! 4. xmlns:xs~="http://www.w3.org/2001/XMLSchema-~nstance~~ 5. xmlns:context=1~http://www.springframework.org/schema/contextrr 1 6. xsi:schemaLocation="http://www.springfraework.org/schema/beans 7. http://www.springframework.org/schema/beans/spr1ng-beans-2.5.xsd 8. http://www.springframework.org/schema/context I 9. http://www.springframework.org/schema/context/spr~ng-context-2.5.xsd1r> 10. <bean ~d="ibref cla~s=~~com. neo . spring. bean. Inlstl tueBeanl'> 1 11. <property name=I1name "> 12. <value>Naresh I Technologies</value> 13. </property>

I 14. <property name=rrfacul tyNames Ir> 15. <list> 16. <value>sekhar</value>

' I 17. <value>lnrao</value> 1 18. <value>narayana</value> * -

19. </list> =I

20. </property> 21.

' I -

22. <property name="courseNamesn> ? 1 * 23. <list>

0 $ 24. <value>spring</value> 2 O r

25. <value>struts</value> 9) I

26. <value>hibernate</value> 27. </list> 1 28. </property>

! 3 4-

29. ,r' I 30. </bean> 31. </beans> I Client.iava 1. package com.neo.spring.client; 1 2. 3. import org.springframework.context.support.AbstractApp1icationContext; 4. import org.springframework.context.support.ClassPathXmlApplicationContext;

\ I 5 . import com.neo.spring.bean.InistitueBean; 6. 1 7. public class Client {

8. 1 9. private static AbstractApplicationContext context = new i

10. ClassPathXmlApplicationContext( 11. 11com/neo/spring/config/applicationContext.xmlr1);

I - 12. 13. public static void main (String[] args) { I 1 14. Inis ti tueBean bean = ( Inis ti tueBean) 15. context. getBean ( I1ibref ) ; 1 16. bean. displayDetails () ; 1

\

17. 1 18. ) F

I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 *

An IS0 9001 : 2000 Certified Company - - - - - - - - - . . - - -. -. . - -- -- 1-

'Page 2 http://javabynataraj.blogspot.com

Page 65: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - - - - -. .

! Spring-IOC By Mr. SomasekharReddy[Certified Professional) 1

1 Iniectinq List obiect (where list contains user defined obiect tvues)

" ;, .. - 1 r @ IiEobjcdit i ject ian B @? trc

1 ij? c~t i i .n~c .s .p~- ing ,hean ::, i ~ : l [rallegc.ja~s;a

?..,.,

I ;. Li,: Stu c1cnt.j ae,tl

, c.oni.tiec.:prii?y.clier7t

.- i$ C.lient ,ja~~.-~a

I +B, cctii.neo,spriny,config

,<.:$ applicati~~.tic'ont~&.xt-111

1 ;. &,; JEE 5y.stem Libra :i &: Spring 2.5 CGIY . . . . . . . . . I C

Sti~dent.iava 1 1. package corn.neo.spring.bean; 2. 3. public class Student { I 4. private int sno;

- 5. private String sname ; 1 6. private double fee ;

- 7. publlc int getSno() {

return sno; 10. 1 1 11. 12. public void setSno(int sno) {

( 13. thls.sno = sno; ' 14. 1 15. 1 16. public String getsname ( ) {

17. return sname ; 1- 18. 1 19.

public void setsname (String sname) this. sname = sname ;

22. 1 1 23. 24. public double getFee() { 1 25. return fee; 26. 1 27. I 28. public void set~ee (double fee) {

29. this.fee = fee; 1 30. 1 - -31.

33.

I . CoHeqe.iava 1. package corn.neo.spring.bean;

I 2.

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I I .. - --- An I S 0 9001 : 2000 Certified Company

Page 3 J

http://javabynataraj.blogspot.com

Page 66: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- . -. . -. . . . . - . . . - - -..

Spring-IOC - By Mr. SomasekharReddy(Certified Professional) 3'

3. import java.uti1. Iterator; 4. import java.uti1 .List; 5. 6. public class College {

7 . private String name ; 8. private List<Student> students; 9. 10. public void setName(String name) {

11. this.name = name; 12. 1 13. 14. publlc void setstudents (Lis t<S tudent> students) {

15. this.students = students; 16. 1 17. 18. public void displayDetails ( ) {

19. System.out.println("College Name is : + name); 20. System.out.println("Student details are ....I1) ; 21. Iterator<Student> iterator = students. iterator ( ) ;

22. while (iterator. hasNext ( ) ) {

23. Student student = iterator .next ( ) ;

24. System.out.println(student.getSno()); 25. System.out.println(student.getSname()); 26. System. out .println (student. getFee ( ) ) ;

27. System. out .println ( ) ;

28. 1 29. 30. 1 31. 32. 1

5. xmlns:context=11http://www.springframework.org/schema/contextr1 I

6. xsi:schema~ocation="http://www.springfraework.org/schema/beans 7. http://www.springframework.org/schema/be~s/spring-beans-2.5.xsd 8. http://www.springframework.org/schema/context 9. http://www.springframework.org/schema/context/spring-context-2.5.xsd1r>

! 10. <bean id=llsln class=wcom.neo.spring.bean.Studentll > 11. <property name=llsnow value="lOOl"~/property> I 12. <property name="sname1I> 13. <value>sekhar</value> 1 14. </property> 15. <property name="feeV ~alue=~2500"~/property> 16. I </bean> -

17. 18. <bean 1d=11s2u class=~com.neo.spring.bean.Studentll > I 19. <property name="sn~~~ ~alue="1002~~~/property> 20. <property name="~name~~ value="somull~/property> 21. <property name="feeW value=~5900~X/property>

1 22. </bean> 23. I

IVaresh i Technologies, Opp. Satyam Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842 1 I . -- - - - - - - -- .-

An IS0 9001 : 2000 Certified Company Page 4

http://javabynataraj.blogspot.com

Page 67: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

7- -- -- -. - - -- - . -

Spring-IOC By Mr. SomasekharReddy(Certified Professional)

24. <bean id="s3" class="com.neo.spring.bean.Studentl'> 1 25. <property name="~no'~ ~alue=~~1003'~~/property> 26. <property name="snameV1 value="somasekhar nX/pr~perty>

( 27. <property name=" fee I' ~alue=~~4200 l1~/property> I 28. </bean> , 29. I 30. <bean ~d="collegeNameRef" ~lass=~~3ava.lang.Strlng">

31. <constructor-arg value=,,Sri Indhu CollegeN /> 1 32. </bean>

33. 34. <bean ~d="college" class=l'com.neo.spring.bean.College'l> 1 35. <property name="namel' ref=llcollege~ame~ef "></property> 36. <property narne="s tudents 'I>

1 37. <list> 38. <ref bean='lsl" />

1 39. <ref bean="s2I1 /> 40. <ref bean="s3" /> 41. </list>

I 42. </property> 43. </bean>

1 44. - 45. </beans>

I Client.iava - 1. package com.neo.spring.client;

1 2. import org . springf ramework . context. support .AbstractApplicationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext;

1 4 . import com . neo . spring. bean. College ; 5. public class Client {

6. ! 7. private static AbstractApplicationContext context = new 8. ClassPathXmlApplicationContex t (

I 9 - ~~com/neo/spring/config/applicationContext.xml1v); 10. 11. public static void main (String[] args) {

I 12. College college = (College) context. getJ3ean ("college1') ;

I 13. college. displayDetails ( ) ;

1 14. 1 15. )

I I

Outuut. College Name is : Sri Indhu college 1 Student details are . . . . 1001

I sekhar 2500.0

1003 1 somasekhar 4200.0

I i IVaresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I _ _. . . _. - An IS0 9001 : 2000 Certified Company

Page 5 http://javabynataraj.blogspot.com

Page 68: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

pp -- - -. --

I Spring-IOC By Mi-. SomasekharReddy (Certified Professional) :' i I Set Primitive Iniection

I I

5: &, JRE System Librat y [JAVA]

$3; &2 Spring 2,5 Cure Libraries

1nstituteBean.iava 1. package com.neo.spring.bean; 2. import java.util.1terator; 3. import java. util . Set; 4 . public class InstituteBean {

5. private String name; 6. prlvate Set<String> facultyNames; 7. private Set<String> courseNames; 8. public void setName (String name) {

9. this .name = name; 10. 1 11. public void setFacultyNames(Set<String> facultyNames) {

12. this.facultyNames = facultyNames; 13. 1 14. public void setCourseNames(Set<String> courseNames) {

15. this.courseNames = courseNames; 16. 1 17. public void dispalyDetails(){ 18. System. out. println (I1Institute name : "+name) ; 19. System. out .println (llfaculty names. . . . If) ; 20. for (String facultyName : facultyNames) {

21. System. out.println (facultyName) ; 22. 1 23. System. out .println (llcourse names. . . . It) ; 24. Iterator<String> iterator=courseNames.iterator() ; 25. while (i terator . hasNext () ) {

26. String courseName=iterator.next(); 27. System. out .println (courseName) ; 28. 1 29. 1 30.

I a~~licationContext.xml - 1. < ? x m l version=I1l. 0" en~oding=~UTF-8~'?> 2. <beans I 3. xmlns=11http://www.springframework.org/schema/beans" 4 . xmlns:xsi=11http://www.w3.org/2001/XMLSchema-instance11 5. xsi:schemaLocation=11http://www.springframework.org/schema/beans

T 6 . http://www.springframe~ork.0rg/~~hema/bean~/~pring~beans-2.5.xsd~~> I 7.

Naresh i Technologies, Opp. Satyam theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 -- .

An I S 0 9001 : 2000 Certified Company

http://javabynataraj.blogspot.com

Page 69: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- - - - - . - - -

I Spring-IOC By Mr. ~ o m a s e k h a r ~ e d d ~ ( ~ e r t i f i e d Professional)

<bean id=I1ibref class="com. neo . spring. bean. InstltuteBeanrl> <property name="namefl value="Naresh I ~ e c h n o l o g i e s ~ ~ ~ / p r o p e r t y >

<property name=I1f acultyName~~~> <set>

<value>sekhar</value> <value>lnrao</value> <value>narayana</value>

</set> </property> <property name="c~urseNames~~>

<set> <value>spring</value> <value>struts</value> <value>hibernate</value>

</set> </property>

</bean> </beans>

Client.iava 1 1. package com.neo.spring.client; ' 2. import org.spr~ngframework.context.support.AbstractApplicationContext; -

3. import org.springframework.context.support.ClassPathXmlApplicationContext; 1 4. import com. neo . spring-bean . InstituteBean; - 5. public class Client {

1 6. private statrc AbstractEpplicationContext contexenew 7. ClassPathXmlApplicationContext( 8. ncom/neo/spring/config/applicationContext.xml~~); 1 9. public statrc void main (String[] args) (

10. InstituteBean bean= (InstituteBean) context. getBean ("ibref IT) ;

1 11. bean.dispalyDetails(); 12.

1 3 . 1

outuut I Institute name :Naresh I Technologies

faculty names.... 1 sekhar lnrao narayana

I course names. . . . spring

I struts I hibernate

Set Obiect Iniection 1 . . . . , 3-.& . . setobjectinjection

: . @.-@ . src , . . I . , . @@com.neo.spring.bean , . ..... . . - . . : ! g. $J college,java , . ; ! ., ? . . ] : . . . : ; &i.$JStudsnt,java i j

i @-& com.neo.spring.client ! . ! : : : $j..i:$-+J . . . . . , ! t i

Client, java I Lrr fR com.neo.rpring.con~ig ! 5 : . . . . . . . . , , . - . -$2 applicationcontext .xml 1 JRE System Library [JAVA]

; . L%-.& Spring 2.5 Cora Libraries - ..................................................

1 Naresh I Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I._..- An IS0 9001 : 2000 Certified Company

- - -- -- - - - - - . -. . . . . . . . - ..... - . -. . -. .......... - . -. . - - -. - P a r

http://javabynataraj.blogspot.com

Page 70: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Student.iava 1. package com.neo.spring.bean; 2. public class Student {

3. private int sno ; 4. private String sname; 5. private String fee; 6. publicintgetSno0 {

7. return sno; 8. 1 9. public void setSno(int sno) {

10. this. sno = sno ; 11. 1 12. publlc String getSname ( ) {

13. return sname; 14. 1 15. public void setsname (String sname) {

16. this.sname = sname; 17. 1 18. public String getFee() {

19. return fee; 20. 1 21. public void setFee(String fee) {

22. this.fee = fee; 23. 1 24. 1

I

Colletae.iava 1. package com.neo.spring.bean; 2. import java.util.Iterator; 3. import java .util . Set; 4. public class College {

5. private String name;

I ' 6. private Set<Student> students; 7. public void setName (String name) {

this.name = name; 1 ;: 1 1 10. public void setStudents(Set<Student> students) I ' 11. this. students = students ; 12. 1 13. public void displayDetails () { 14. System. out .println ( l l ~ ~ l l e g e name: "+name) ;

15. System.out.println("Student details...."); 16. Iterator<Student> iterator=students.iterator(); 17. while (iterator. hasNext ( 1 ) { 18. Student student=iterator.next() ; 19. System. out .println (student. getSno 0 ) ; 20. System. out .println (student. getSname () ) ; 21. System. out.println(student.getFee() 1 ; 22. System. out.println ( ) ;

23. 1 24. 1

1 2 5 . 1

auulicationContext.xmI I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 An I S 0 9001 : 2000 Certified Company I _ - . - -. __ I --

Page 8 http://javabynataraj.blogspot.com

Page 71: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

' spring-lOC By Mr. ~ o r n a s e k h a r & d d ~ ( ~ e r t i f i e d Professional) i I

1. <?xml version="l . O w en~oding=~~UTF-8~~?> I 2. <beans 3. mlns=rrhttp://www.springframework.org/schema/beans'r 1 4. xmlns : x~i=~~http: //www . w3. org/2001/XMLS~hema-instance~~ 5. xsi:schemaLocation=trhttp://www.springfrework.org/schema/beans 6. http://www.springframework.org/schema/beans/spring-beans-2.5.x~d~~> i 7. 8. <bean id="slU ~lass=~~com.neo.spring.bean.Student">

I 9. <property name="sno" value="1001"~/property> 10. <property name=lrsnarne" ~alue=~~sekhar~~X/property>

/ 11. <property name="£ een value="2500rrX/property> ' 12. </bean> 13. 1 14. <bean id=Irs2lr ~lass=~~com. neo. spring. bean. Studentrr> 15. <property name="snorr value="1002"~/property>

/ 16. <property name=frsnamert val~e=~~somu~~~/property> 17. <property name="feerr value="2500r1~/property> 18. </bean>

I 19. 20. <bean id=1ts3rr ~lass=~~com. neo. spring. bean. Studentrr> 1 21. <property name="snow ~alue="1003~~/property>

-- 22. <property name="snamen value="somasekharrr~/property>

1 23. <property name="feew v a l ~ e = ~ ~ 2 5 0 0 ~ ~ / p r o p e r t y > 24. </bean>

7 25. I 26. <bean id=rrcollegeref" class=~com.neo.spring.bean.Collegetr>

27. <property name=rrnamerr val~e=~lSri Indhu Collegerr~/property> 1 28. <property name="studentsn> 29. <set> 30. <ref bean="slrr/> I 31. <ref bean="s2Ir/> 32. <ref bean="s3"/> 1 33. </set> 34. </property> 1 35. </bean> 36. </beans>

I Client.iava 1. package com.neo.spring.client; 1 2. import org . springframework. context. support .AbstractApplicationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 1 4. import com.neo.spring.bean.College; 5. public class Client {

6. private static AbstractApplicationContext context=new 1 7 . ClassPathXmlApplicationC~ntext(~~

8 . com/neo/spring/config/applicationContext.xml~r); 1 9. public static void main (String[] args) {

- - 10. College college= (College) context. getBean (rrcollegeref It) ;

' 1 ::: college. displayDetails ( ) ;

1

I 13- O U ~ D U ~ I college name: Sri Indhu College Student details. . . .

1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L An IS0 9001 : 2000 Certified Company . . - . - -

Page 9 http://javabynataraj.blogspot.com

Page 72: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Spring-IOC -

- -. - .. .. .- . .. . . .. - . .. . - By Mr. SomasekharReddy(Certified ~ r o f e s s i o n a l ) ~ ~ ' I

sekhar 2500

1003 somasekhar 2500

9 arrayprimitisreinjection . . . . . .. ..

~ ~ 2 . .53q src . , . . .

: i$ com.neo.spring. bean . . . . . ! *:..

3:. . InstituteBean, java : : < . . ; . r . I-i . f# com.neo, spring , client . . : ......,

, . . . . .

> 15 Client. java

: . :-3. rc com ,neon spring, sonfig : . . . . . . . ! c .;-:' applicationrIontext.xml ) . i&-,E&k . JRE System Litvary [JAVA]

; I%] ,&& Spring 2.5 Core Libraries . -

Arrav Primitive Iniection

InstituteBea n.iava 1. package com.neo.spring.bean; 2. public class InstituteBean {

3. private String name; 4. private String[] facultyNames; 5. private String[] courseNames; 6. public void setName(String name) {

7. this.name = name; 8. 1 9. public void setFacultyNames (String [I f acultyNames) {

10. this.facultyNames = facultyNames; 11. 1 12. public void setCourseNames(String[] courseNames) {

13. this.courseNames = courseNames; 14. 1 15. public void dispalyDetails(){ 16. System. out. println (vvInstitute name : "+name) ; 17. System. out.println (nvfaculty names. . . . l') ; 18. for (String facultyName : facultyNames) {

19. System. out. println (facultyName) ; 2 0 . 1 21. System. out .println ("course names. . . . In) ; 22 . for (String courseName : courseNames) {

23. System. out. println (courseName) ; 24. 1 25. 1 26. 1

Naresh i Technologies, Opp. Satyam theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 -- -. - - -- - -

An IS0 9001 : 2000 Certified Company Page 10

http://javabynataraj.blogspot.com

Page 73: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

<bean id="ibrefW class="com.neo.spring.bean.InstituteBeanvl> <property n~me=~lname~~ val~e=~~Naresh I Technologies property>

<! -- <property name=llfacultyNamesll> <set>

<value>sekhar</value> <value>lnrao</value> <value>narayana</value>

</set> </property> <property name="co~rseNames~~>

<set> <value>spring</value> <value>struts</value> <value>hibernate</value>

</set> </property> --> <property name=llfacultyNamesll>

<list> <value>sekhar</value> <value>lnrao</value>

Client.iava 1 1. package com .neo . spring. client; 2. import org.springframework.context.support.AbstractApp1icationContext; 1 3. import org.springframework.context.support.ClassPatbXmlEpplicationContext; 4. import com.neo.spring.bean.InstituteBean; 5. public class Client {

1 6. private static AbstractApplicationContext context=new , 7 . ClassPathXmlApplicationContext (

I 8 . 11com/neo/spring/config/application~ontext.xml11); - - 9. public static void main (String[] args) {

10. Ins ti tuteBean bean= (Ins ti tuteBean) con text. getBean ( l1ibref 'I) ; bean.dispalyDetails();

12. 1 1 1 3 . 1

1 OlJt~Llt ' Institute name:Naresh I Technologies

I Naresh i ~ e d n i o l o ~ i e r , Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L - - --- - An I S 0 9001 : 2000 Certified Company --

Page 11 I

http://javabynataraj.blogspot.com

Page 74: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-1

Spring-IOC By Mr. SomasekharReddy(Certified ~ ro fe s s iona l )~ I

f a c u l t y names . . . . sekhar l n r a o narayana course names . . . . s p r i n g s t r u t s h i b e r n a t e

Arrav Obiect Iniection :-. .-, .AII_~ ,-- at - . ra.::.ot~jectir~jection -

.... \ f-j @ src

. . i , et . I-?? : (...,. a2 corn.nea. t:pring. hean

. . . . . I+; College.ja-::a . .

? ' . ; :.A $j Student.java

: i [3. .& corn,neo, spring,client , > . ,. .,

: . :*; ~:lisnt. ja-v-a : < ... ". . , -* .,

: 13 ,it.-, corn. neo, spring. config

..;. -, applisetionContext .xml

; r$&. JRE 5ystem Littrary [JAVA]

j I'H @& Spring 2.5 Core Libraries , - , . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . , . . . . . . . . . . . . . . . . . . .

Student.iava 1. package com.neo.spring.bean; 2. p u b l i c c l a s s Student {

3. p r i v a t e i n t sno; 4. p r i v a t e S t r i n g sname; 5. p r i v a t e S t r i n g f ee ; 6 . p u b l i c i n t getSno() {

7. r e t u r n sno; 8. 1 9 . p u b l i c void s e t s n o ( i n t sno) {

10. t h i s . s n o = sno; 11. 1 12. pub l i c S t r i n g getSname ( ) {

13. r e t u r n sname; 14. I 15. p u b l i c void setsname (S t r ing sname) 16. this .sname = sname; 17. 1 18. p u b l i c S t r i n g ge tFee( ) {

19. - r e t u r n f ee ; 20. 1 21. p u b l i c void se tFee (S t r ing f e e ) {

22. t h i s . f e e = f e e ; 23. 1 24. 1

Collec~e.iava 1 1. package com.neo.spring.bean; 2. p u b l i c c l a s s College {

3. p r i v a t e S t r i n g name; I 4. p r i v a t e Student [ I s t uden t s ; 5. p u b l i c void setName ( S t r i n g name) { I

- - Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1

I - - An I S 0 9001 : 2000 Certified Company -- -- -

Page 12 http://javabynataraj.blogspot.com

Page 75: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- -. . . . - -- . . .

Spring-IOC . ... .-

By Mr. SomasekharReddy(Certified Professional)

this.name = name; 1 public void setStudents(Student[] students) {

this.students = students; 1 public void displayDetails () {

System. out .println (TTcollege name: "+name) ; System. out .println ("Student details. . . . It) ; for (Student student : students) {

System. out.println (student.getSno ( ) ) ;

System. out.println (student.getSname0 ) ; System. out.println (student.getFee ( ) ) ;

System. out .println ( ) ;

1 1

1

a~ulicationContext.xmI 1. <?xml ~ersion=~~l. 0" en~oding=~~UTF-8~'?> 2. <beans 3. xmlns=~~http://www.springframework.org/schema/beans~~ 4. xmlns:xsi=~1http://www.w3.org/2OO1/X~~Schema-instance~~ 5. xsi:schema~ocation="http://www.springframework.org/schema/beans 6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsd~~> 7. 8. <bean id="slfl class=~com.neo.spring.bean.Studentl~> 9. <property name="snon value=l~lOO1~X/property> 10. <property name="snamen value="sekharn~/property> 11. <property name="f eew ~alue=~~2500~~~/property> 12. </bean> 13. 14. <bean id="s2" class=~com.neo.spring.bean.Studentn> 15. <property name=vvsnon val~e=~1002"~/property> 16. <property name="snamePl value="~omu~~~/property> 17. <property name=Ivf eel1 value="2500 "X/property> 18. </bean> 19. 20. <bean id="s3" ~lass=~com. neo . spring. bean. Student"> 21. <property name="snon value="1003"~/property> 22. <property name="snamen value="somasekhar"~/property> 23. <property name="f eelf val~e=~~250 0 lv~/property> 24. </bean> 25. 26. <bean ~d=~~collegeref lv cla~s=~~com. neo . spring. bean. College"> 27. <property name=ltnameV value="Sri Indhu C~llege~~/property>~ 28. <property name="students"> 29. <!-- <set> 30. <ref bean=Ifsl "/> 31. <ref bean="s2"/> 32. <ref bean=rus31f/> 33. </set> --> 34. <list> 35. <ref bean="slW/> 36. <ref bean="s2"/> 37. <ref bean="s3"/>

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I An IS0 9001 : 2000 Certified Company . - - - - - -. . --

Page 13 http://javabynataraj.blogspot.com

Page 76: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - - - - - -

Snrinz- I9 C Bv Mr. SomaseltharReddy[Certified Professional) '

Client.iava 1. package com.neo.spring.client; 2. import org.springframework.context.support.AbstractApp1icationContext; 3 . import org.springframework.context.support.ClassPathXmlApplicationContext; 4. import com.neo.spring.bean.Col1ege; 5. public class Client {

6. private static AbstractApplicationContext context=new 7. ClassPathXmlApplicationContext( 8. "com/neo/spring/config/app~icationConte~t.~~~~); 9. public statxc void main (String[] args) {

10. College college= (College) context. getBean ( "collegeref ") ; 11. college.displayDetails(); 12. 1 13. 1

Outuut college name:Sri Indhu College Student details . . . . 1001 sekhar 2500

1003 somasekhar 2500

Mar, Primitive Iniection

W @ com.neo.spring. bean lu ,S j InstituteEean, java

Id P& cor11.ne0, spring .client

W Cl~ent . java

B com.neo,sprinq.confiq ,~-2 appl~cationContext .xml

&d E& JRE System Library [JAVA]

LB Spring 2.5 Core Libraries

1nstituteBean.iava 1. package com.neo.spring.bean; 2. import java.util.1terator; 3. import java.uti1 .Map; 4. import java .util . Set; 5. public class InstituteBean {

6. private String name;

. .

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 An IS0 9001 : 2000 Certified Company I

Page 14 http://javabynataraj.blogspot.com

Page 77: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

By Mr. SomasekharReddy(Certified ~rofessional)

private Map<Integer , String> facul tyMap; private Map<Integer, String> courseMap; public void setName(String name) {

this.name = name; 1 publlc vold setFacul tyMap (Map<Integer , String> f acul tyMap) {

this. f acul tyMap = f acul tyMap ; 1 public vold setCourseMap(Map<Integer, String> courseMap) {

this. courseMap = courseMap; 1 public void dispalyDetails(){

System. out. prlntln ("Institute name : "+name) ; System. o~t.println(~~facu1ty names.. . . . ") ;

Set<Integer> facultyKey=facultyMap.keySet(); Iterator<Integer> iteratorl=facultyKey.iterator(); whlle (iteratorl . hasNext ( ) ) {

Integer facultyId=iteratorl .next () ; String facultyName=facultyMap.get(facultyId); System. out .println (f acultyId+"-->~l+facultyName) ;

1 System. ~ut.println(~~course details . . . . . ") ; Set<Integer> courseKey=courseMap.keySet(); Iterator<Int.eger> iterator2=courseKey.iterator(); while (iterator2.hasNext()) {

Integer courseId = iterator2.nextO; String courseName=courseMap.get(courseId) ; System. out .println (courseId+ll-->l~+~~urseName) ;

1 1

1

I -. a~~licationContext.xml 1. <?a1 versi~n=~l.O" en~oding=~lUTF-8~?> / 2. <beans 3 . xmlns=~http://www.springframework.org/schema/beans~ 4 . xmlns:xsi=~http://www.w3.org/2O01/XM~Schema-instance~ 1 5. x s i : s c h e m a L o c a t i o n = " h t t p : / / w w w . s p r i n g f r ~ a / b e a n s 6. http://www.springframework.org/schema/beans/spring-beans-2.5.x~d~~> I 7- 8. <bean id="ibrefw ~lass=~~com. neo . spring. bean. InstituteBeanI1> 9. <property name="nameV value=I1Naresh I Technologies"X/property> I 10. <property name=I1f acul tyMapI1> 11. <map> 1 12. <entry key=vlOO1 " ~alue=~~sekhar"X/entry> 13. <entry key=m1002t1 ~alue=~~lnrao~~></entry> 1 14. <entry key=n1003n value="narayananX/entry>

- - 15. </map> 16. </property> 17. <property name=ncourseMapll> 18. <map> 19. <entry key=wllll"> 2 0 . <value>spring</value> 21. </entry> 22. <entry key=n111211>

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

-. - - -- ---- Page 15

http://javabynataraj.blogspot.com

Page 78: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

r-y-- ' . - . . . . . . . . . . . - - - -. - . .- -.-A

Spring-IOC By MI-. SomasekharReddy(Certified Professional) -7 - " .. . . . .. .. . .. . . -. ., .-

/ 23. <value>struts</value> 1.

24. </entry> 25. <entry key="1113">

I . 26. <value>hibernate</value> 27. </entry> 1 -:

i 28. </map> 1 29. <;property> I 30. </bean> 31. </beans> I , ~

Client.iava i

i 1. 2ackage com.neo.spring.client; I . 2. import org.springframework.context.support.AbstractApp1icationContext;

, 3. import org.springframework.context.support.ClassPathX~nlApplicationContext; I 4 . import com.neo.spring.hean.1nstituteBean; 5. public class Cllent {

6. private static AbstractApplicationContext contexenew 7. ClassPathXmlApplicationContext( 8. "com/neo/spring/config/applicationConte~t.xml~~) ;

9. public static void main (String[] args) {

10. Ins ti tuteBean bean= ( Ins ti tuteBean) con text . getBean ('libref IF) ; 11. bean. dispal yDetails ( ) ;

12. 1 13. 1

Output ':i'"Institute name:Naresh I Technologies faculty names..... 1001-->sekhar 1002-->inrao 1003-->narayana course details . . . . . 1111-->spring 1112-->struts 1113-->hibernate

m g 7' 24 stc

: . . . ~ $ ,& com.neo.spriny.hean I . . . : . ' . + l [xi C&ge.java ? : : . . .. .., : . . . ; ; iE. & Studcnt.ja-.,a : ! I

: : &j -@ com.neo.spring. client . . . . ,

. i . : . i . [E. % client.java : , , . .

:' 2 ,& com.neo, spring, config , , . . . . . . . t , , applicationContext.xml I $1 t-" JRE System Library [JAVA]

; sg-.-& Spring 2.5 Cure Libraries I I

Student.iava 1. package com.neo.spring.bean; 2. public class Student {

3. private int sno; 4. private String sname; 5. private String fee;

Mar, Obiect Iniection

- --- - - IVar-esh i Technologi?~, Opp. Satyam Theatre, Ameerpet, Hyderahad, Ph: 040-23746666,23734842 1 I-- -- - - - - - An IS0 9001 : 2000 Certified Company i I

Page 16 http://javabynataraj.blogspot.com

Page 79: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

sPTng-IOC By Mr. SomasekharReddy(Certified Professional) I

--. . - - . .

public int getSno() {

return sno;

1 public void setSno(int sno) {

this.sno = sno; 1 public String getsname ( ) {

re turn sname ;

1 public void setSname(String sname) {

this.sname = sname; 1 public String getFee() {

return fee; 1 public void setFee(String fee) {

this.fee = fee; 1

1

Colleae.iava 1. package com.neo.spring.bean; 2. import java.uti1. Iterator; 3. import java.util.Map; 4. import java.util.Set; 5. public class College {

6. private String name; 7. private Map<Integer, Student> studentMap; 8. public void setName (String name) {

9. this.name = name; 10. 1 11. 12. public void setStudentMap(Map<Integer, Student> studenmap) {

13. this.studentMap = studentMap; 14. 1 15. 16. public void displayDetails ( ) {

17. System. out. println (I1college name: "+name) ; 18. System. out .println ("Student details. . . . ") ; 19. Set<Integer> studentKey=studentMap.keySet(); 20. I terator<Integer> iterator=s tudentKey . iterator ( ) ; 21. while (iterator. hasNext ( ) ) {

22. Integer studentId=iterator.next(); 23. System. out .println (studentId) ; 24. Student s tudent=s tudentMap . get (s tudentId) ; 25. System. out .println (student. getSno () ) ;

26. System. out .println (student. getSname ( ) ) ;

27. System. out.println(student.getFee()) ; 28. System. out.println() ; 29. 1 30. 1 31. 1

1 - Naresh i ~echnoio~ies, opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I An IS0 9001 : 2000 Certified Company L-- . --. - - - - -

Page 17 http://javabynataraj.blogspot.com

Page 80: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

. . . . . . . . . -. . - - - - - . . . -

Spring-IOC By Mr. ~ o m a s e k h a r ~ e d d ~ ( ~ e r t i f i e d Professional) ,--'.

I I -1

A, , 2. <beans 3. ~mlns=~~http://www.springframework.org/schema/beans~~ 4 . xmlns:xsi=11http://www.w3.org/2O01/XMLSchema-instance11 I , 5. xsi:schemaLocat~on=11http://www.springframework.org/schema/beans 6. http://www.spr~ngframework.org/schema/beans/spring-beans-2.5.xsd1'> 1 7. 8. <bean ~ d = ~ ~ s l " cla~s=~~com. neo . spr~ng .bean. Studentw> ,- 1 9. <property name=l1snol1 ~alue="lOOl~~~/property> 10. <property name=llsname" ~ a l u e = " s e k h a r ~ ~ ~ / p r o p e r t y > 11. <property name=I1f eel1 ~a lue=~~2500"X/proper ty>

I 12. </bean> 13. 1 14. <bean 1d="s2" class=llcom.neo.spring.bean.Student"> 15. <property name=llsnoll ~ a l u e = ~ ~ 1 0 0 2 " ~ / p r o p e r t y > 1 16. <property name=llsnamell value=llsomun~/property> 17. <property name=I1f eel1 value="250 0 ll~/property> 18. </bean> I 19. 20. <bean ld="s3" cla~s=~~com. neo . spring. bean. Studentv1> 1 21. <property name="snol1 value="1003"~/property> 22. <property name=l1snamel1 ~alue=~~somasekhar~~~/property> I 23. <property name=llfeell ~alue="2500~~X/proper ty> -

24. </bean> 25. I 26. <bean id="~ollegeref~~ class=llcom.neo.spring.bean.College"> -

27. <property name="namen value=I1Sri Indhu ~ollege"~/property> 1 28. <property name=rlstudentMapll>

/'

29. <map> \ I 30. <entry key=I1llll1l ~alue-ref=~~sl~~>

I

31. </entry> 32. <entry key=n1112" > 1 33. <ref bean="s2I1/> 34. </entry> 35. <entry key=11111311>

; I 36. <ref bean="s3"/> 37. </entry> 38. </map>

'1 39. </property> I 40. </bean> 41. </beans> i Client.iava 1. package com.neo.spring.client; 1 2. import org.springframework.context.support.AbstractApplicationC~ntext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; I 4. import com.neo.spring.bean.College; 5. public class Client {

6. private static AbstractApplicationContext context=new I -

7. ClassPathXmlApplicationContext( 8. 11com/neo/spring/config/applicationContext.xml11); I 9. public static void main (String[] args) {

10. College college= (College) context. getBean ("collegeref 11) ; 11. college. displayDetails ( ) ;

I 12. 1 13. )

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 - I

! An IS0 9001 : 2000 Certified Company L .- . -. . - - - -. - - . . - - - -. .. . . . . . . . . . - -. .- .- --- . -. -- ..I

Page 18 http://javabynataraj.blogspot.com

Page 81: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- .- - -- --

Spring-IOC By Mr. Somasekhal-Reddy(Certified fiofessional]

I output college name : Sri Indhu College Student details . . . . 1 1111 1001 1 sekhar 2500

1 somasekhar 2500

Properties Primitive Iniection

. . / . . . 9. $3 com.neo,spring.hean . . ?

: : 3.. ;:a DataEasePr~nperties, jaria < - 3 . . & - - a, cum, neo, spring, client

: . , . . . . . . >B.. client,java . , . . , . ! : : . . B.-.g& com.neo.sprir~g,conFig

, . . . . .

, >*

. . ,-.+A? applicationContext. xrid

i C$f-.&h JRE System Library [JAVA] r <a..-& 5prirly 2.5 c,:~rs Libraries

DataBasePro~erties.iava 1. package com.neo.spring.bean; 2. import java.util.Enumeration; 3. import java.util.Properties; 4. public class DataBaseProperties {

5. private Properties &Properties; 6. public void setDbProperties(Properties &Properties) {

7. this.dbProperties = &Properties; 8 . 1 9 . public void dispalyDetails ( ) {

lo. Enumeration enumeration-&Properties .keys () ; 11. while (enumeration.hasMoreElements()) { 12. String id=(String)enumeration.nextElement(); 13. String name=dbProperties.getProperty(id); 14. System. out. println (id+rf-->lr+name) ;

15. 1 16. 1 17. )

licationContext.xml I ?l)<?xml ~ersion=*~l. 0.' encoding="UTF-B"?> 1 2. <beans 1 3. xmlns=~1http://www.springframework.org/schema/beans~r 4. xmlns:xsi=~1http://www.w3.org/2OO1/XMLSchema-instance~

Naresh i Technologies, atyarn yarn Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

1 ---. -- - - An IS0 9001 : 2000 Certified Company - - - -- . - - -

Page 19 http://javabynataraj.blogspot.com

Page 82: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - - - . -. - - - --

S~rinrr-IOC Bv Mr. SomasekharReddvfCertified Professional1 , '

Client.iava 1. package com.neo.spring.cllent; 2. import org.springframework.context.support.AbstractApp1icationContext; 3. import org.springframework.context.support.ClassPatNtmlApplicationContext; 4. import com.neo.spring.bean.DataBaseProperties; 5. public class Client {

6. private static AbstractApplicationContext context=new 7. ClassPathXmlApplicationContext( 8. 1~com/neo/spring/config/application~ontext.xm~11); 9. public static void main(String[] args) {

10. DataBaseProperties bean=(DataBaseProperties) 11. context. getBean ( "ibref ") ; 12. bean. dispalyDetails ( ) ;

13. 1 14. }

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 -

An IS0 9001 : 2000 Certified Company I -- - -

Page 20 http://javabynataraj.blogspot.com

Page 83: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- ----

Spring-IOC By Mr. ~omaselthyr~edd~(~ertified - - . -. . -- Professional)

I Externilize properties from sprinq confiquration file

I c-; . .<''L& L*.. - 5rC

j : . a- & curi~.neo.spring, bean ' . *... . j : + i !. . lJ.5 I.. ..I [)BPropertiesEean.java

spring, client > . ., ,.... " . : . . : 13.; !,['I CJier~t. jay3 . . . . , 1 i . . . , . bi@ . com.neo.rprir~g.rmAg , . . .

:.;: .;' applicationContextt;~nil

~. . . . . . . , . dbpf'lrlperties,properties

1 & & IRE 5ystem Library [ IAVA] < .

j &I .-a Spring 2.5 Core Libraries G .-

I DBPro~ertiesBean~iava I 1. package com.neo.spring.bean;

, 1 2. public class DBPropertiesBean {

3. private String username ; ' 4. private String password; I - 5. private String url ; 1 6. private String driverclass; 7. public void setUsername(String username) {

- 8. this.usernarne = username; 1 I 9 .

10. public void setPassword(String password) { I 11. this.password = password; 12. 1 13. public void setUrl (String url) { I 14. this.ur1 = url; 15. 1

1 16. public void setDriverClass(String driverclass) {

17. this.driverClass = driverclass; 18. 1 19. public void displayDetails(){ 20. System. out. println (username) ; 1 21. System. out .println (password) ; 22. System. out.println (url) ;

1 23. System. out.println (driverclass) ; 24. 1

125. ?

db~Properties.properties I I. un=acott 2. pwd=tiger

' 1 3. url=jdbc: oracle: thin: @localhost: 1521 : server - - 4. dc=oracle.jdbc.driver.OracleDriver

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I L - - - - -- --

An IS0 9001 : 2000 Certified Company Page 1

http://javabynataraj.blogspot.com

Page 84: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - - - - -

1 Spring-IOC By Mr. Son?asekharReddvCCertified Professionall

<bean class="org.springframework.bean~.fa~t~ry.config.Property PlaceholderConf igurerf1>

<property name=lllocation'l value="com\neo\spring\properties\dbp~roperties.properties~~/>

</bean>

<bean id=lldbpropsref" class=~com.neo.spring.bean.DBPropertiesBeanll> <property name="usernameW value="$ { un) "/> <property name=llpasswordll value=11$ { pwd ) "/ > <property name="urlW ~alue="${url)~~/> <property name=lldriverClass" value="$ { dc) "/>

</bean> </beans>

Client.iava 1. package com.neo.spring.client; 2. import org.springframework.context.ApplicationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 4. import com.neo.spring.bean.DBPropertiesBean; 5. public class Client {

6. private static Applicationcontext context-new 7 . ClassPathXmlApplicationContext( 8. 11com/neo/spring/config/applicationContext.xml11); 9. public static void main(String[] args) {

10. DBPropertiesBean bean=(DBPropertiesBean) 11. context. getBean ("dbpropsref If) ; 12. bean. displayDetails ( ) ;

13. 1 14. )

O U ~ D U ~ scott tiger jdbc:oracle:thin:@localhost:1521:server oracle.jdbc.driver.OracleDriver

I I n above application we have only one properties file. So we have t o take <property narne="location" --- , ' : I>. I

I f w e have two properties files then we have t o take <property narne="locations" ---I>. Observe the I

below application. ( I

r I i I

\ \ I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 An IS0 9001 : 2000 Certified Company \

-- --. . - . . - -. -- -- -- 2 Page 2

I http://javabynataraj.blogspot.com

Page 85: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Spring-IOC By Mr. -. SomasekharReddy(Certified - Professional) . . - -. - .. . . - - .. .. -- -. - - I

:$-- $3 com,neu,.;pring,bean

i,r.f. DBPropertiesBean, java ,.-., ;;- g4 corn, neon spring .client

. . . . . . , ,+ , ; 1 : . i.,,.,.i Client. java ;%..g$; corn,r~e~:~,spring,config

. , , ..., .s~lplicatior~Context.xrnl

I .- i.;. [z: curl-~.neo,sprir~g,properties . . . .

: . . dbpPrc1perties.properties 1 ; . . ,

,.. dbpProperties2,properties : &, JRE System Litlrar-:, [JAVA] I i : Ed-,& Spring 2,s Core Libraries. .

DBPropertiesBean.iava 1. package com.neo.spring.bean; 2. public class DBPropertiesBean {

3. private Strlng username; 4. private String password; 5. private String url; 6. private String driverclass; 7. private Strlng vendor; 8. public void setVendor(String vendor) {

9. this.vendor = vendor; 10. I 11. public void setusername (String username) {

12. this.username = username; 13. I 14. public void setPassxord(String password) {

15. this.password = password; 16. I 17. public void setUrl(String url) {

18. this.ur1 = url; 19. I 20. public void setDriverClass(String driverclass) {

21. this.driverClass = driverclass; 22. I 23. public void displayDetails() { 24. System. out .println (username) ; 25. System. out .println (password) ; 26. System. out .println (url) ; 27. System. out . println (driverclass) ; 28. System. out . println (vendor) ; 29. I 30. 1

1 Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company L - --- _ . - .- --

Page 3 http://javabynataraj.blogspot.com

Page 86: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

au~IicationContext.xmI 1. <?xml version="l .0" en~oding=~~UTF-8"?> 2. <beans 3. xmlns="http://www.springframework.org/schema/bean~~~

4. xmlns : ~si=~'http: //www . w3. org/2001/XMLSchema-instance1' 5. xsi:schemaLocation=~http://www.springframework.org/schema/beans

<bean id="dbpropsrefV1 class=llcom . neo . spring. bean. DBPropertiesBean19 <property name="username" ~alue=~'${un)"/> <property name=npasswordll ~alue=~${pwd)"/> <property name=wurlw val~e=~${url)~/> <property name="driverClass" val~e=~${dc)~/> <property name="vendorV1 ~alue=~~${vendor)~/>

</bean> </beans >

Client.iava 1. package com.neo.spring.client; 2. import org.springframework.context.ApplicationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 4. import com.neo.spring.bean.DBPropertiesBean; 5. public class Client {

6. private static Applicationcontext context=new 7. ClassPathXmlApplicationContext( 8. 11com/neo/spring/config/applicationContext.xml1~); 9. public static void main (Stringl:] args) {

10. DBPropertiesBean bean=(DBPropertiesBean) 11. conte~t.getBean(~dbpropsref") ; 12. bean. displayDetails ( ) ;

13. 1 14. )

0llt~llt scott tiger jdbc:oracle:thin:@localhost:1521:server oracle.jdbc.driver.OracleDriver Oracle

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 -

- - - - . - An IS0 9001 : 2000 Certified Company

--

Page 4-I http://javabynataraj.blogspot.com

Page 87: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - --- --

Spring-IOC I -

By Mr. SomasekharReddy(Certified Professional) . -- - I

I dependencv-check

Q . ) I t i s used to verify a l l dependencies o f been t h a t a r e con f i gu red v i a i n j ec t i on a r e i n j e c t e d o r I not?.

To implement dependency checking to a spring bean we make use of 'dependency-check' attribute of <bean> tag. I This attribute takes any one of the four following values.

1) none( i t won't check whether dependencies injected or not) 1 2) sirnple(it checks all primitive dependencies injected or not) 3) ob jects( i t checks all the object type dependencies injected or not)

( 4) al l ( i t checks both primitives and object type dependencies injected or not) I f incase if we forgot t o set any value either primitive or objective type i t raise an exception called 'Unsat isf ied DependencyExcept ion' . i ;2 -'& .depender~cycheck

I i-i. .(,?a I . .... , ....;. J src I".. @

. , . corn. nso ,spring. bean

. . .

I . . . i [s car, ja-,>a , ,

. . f+z -. ..: , ! f f r~ving . java .

. . g2 . f# corn. neo. spring ,client . . , ,

,.. . . I'-"i . i J'' Client. java .*' ! ....... 1

' : - r- 4

< .z.! fE3. corn, neo.spring.config

i I . . applicationcontext .xml : , i+3 . && JRE System Library [JAVA] . 7 i i l - g& Spring 2.5 Core Libraries

Driv inq. iava 1 1 . package corn. neo . spring. bean ;

2 . pub l i c c l a s s Drlvlng {

1 3. p r i v a t e St r ing dr iver ; ' 4. publ ic void s e w r i v e r (S t r ing dr iver) {

5. t h i s . d r i v e r = dr ive r ; 1 6. I

7 . pub l i c S t r ing getDriver() {

1 8. re tu rn d r ive r ; 9. I , 10. I

Car.iava I 1 . package com . neo . spring. bean ;

2. p u b l i c c l a s s Car { 1 3. p r i v a t e S t r ing breaks; 4 . p r i v a t e Driving driving; 5. publ ic void setDriving(Driving driving) {

1 6 . t h i s . d r i v i n g = dr iv ing; 7. I

' 1 8. publ ic void se tareaks (S t r ing breaks) {

- - 9 . th is .breaks = breaks;

I ;:: I publ ic void d r i v e c a r ( ) {

12. System. out . p r i n t l n ("old man come across the road") ; 1 13. System. out . p r i n t l n ("apply breaksu) ;

14. i f (breaks !=null) {

1 15. System. out . p r in t ln ( I f o ld man savedw) ; 16. }else {

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company I-- -- . - _ - . . . . - - - _ _ -

P- http://javabynataraj.blogspot.com

Page 88: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - -- -. - -- -

Spring-!? C By Mr. SomaseltharReddy(Certified Professional) -' I

System. out .println ("old man kicked the bucket") ; 1 if (driving. gemriver ( ) !=null) {

System. out .println ("driver is driving") ; }else {

System. out. println ("owner is drivingrv) ; 1

1

Client.iava 1. package com.neo.spring.client; 2. import org.springframework.context.App1icationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 4. import com.neo.spring.bean.Car; 5. public class Client {

6. private static Applicationcontext context=new 7. ClassPathXmlApplicationContext ( 8. ncom/neo/spring/config/application~ontext.xm~~~); 9. public static void main (String[] args) {

10. Car bean= (Car) context. getBean ("carref ") ; 11. bean. drivecar ( ) ; 12. 1 13. )

O U ~ D U ~ old man come across the road apply breaks old man saved driver is driving

Now observe below applicationContext.xml, here we are not configuring Car class property and giving I dependency-check="simple".

I_

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 An I S 0 9001 : 2000 Certified Company

-- - - - - .-. - - - - - -1 Page 2

http://javabynataraj.blogspot.com

Page 89: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

spring-IOC By Mr. SomasekharReddy(Certified - - - . . - -. -- ~ro fes s iona l ) --

I

<bean id=vrdriveref" class="com . neo . spring. bean. Drivingv1> <property name="driverff value="drivervrX/property> </bean> <bean id=Ivcarref" cla~s=~~com.neo.spring.bean.Car~~

dependency-check="simple"> <property name="drivingm ref=vrdriverefvv/>

</bean> </beans>

Now run the client program and observe we'll get exception i.e., UnsatisfiedDependencyException. I f we are not configuring the Driving class property and giving dependency-check="objects".

a~~licationContext.xmI 1. <?xml version="l .0Iv en~oding="UTF-8~~?> 2. <beans 3 . xmlns="http://www.springframework.org/schema/beans" 4 . xmlns:xsi=~~http://www.w3.org/2001/XMLSchema-instance~v 5. xsi:schemaLocation=vvhttp://www.springframework,org/schema/beans 6. http://www.springframe~ork.0rg/~~hema/beans/spring-beans-2.5.xsd~~> 7. 8. <bean id="driveref Iv class="com. neo . spring. bean. Drivingtv> 9. <property name=lrdriver" ~alue=~~driver"~/property> 10. </bean> 11. <bean id="carref" ~lass=~'com.neo.spring.bean.Car~~ 12. dependency-che~k=~~ob jects "> 13. <property name="breaksn value="nice breaksn/> 14. </bean> 15. </beans>

I Now run the client program and observe we'll get exception i.e., UnsatisfiedDependencyException.

I Global default dependency checking

I Explicitly define the dependency checking mode for every beans is tedious and error prone, you can set a default- 1 dependency-check attribute in the <beans> root element to force the entire beans declared within <beans> root

element t o apply this rule. However, this root default mode will be overridden by a bean's own mode if specified.

1 a~~licationContext.xrnl 1. <?ml version=Ifl . OvI encoding="UTF-8"?> 1 2. eeans

- - 3. xmlns=vvhttp://www.springframework.org/schema/beansvv

I 4 - xmlns:xsi=~~http://www.w3.org/2001/XMLSchema-instance~~

5. xs i : s chemaLocat ion="ht tp : / /www.spr ingfr~ .org / schema/beans 6. http://www.springframework.org/schema/beans/spring-beans-2.5.xsdvv

1 7 . default-dependency-che~k='~aIIII> 8 .

1 9 . <bean id="driverefvr ~lass=~~com.neo.spring.bean.Driving"> 10. <property name=Ivdriver" ~alue=~~driver~X/property>

i Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I..-_ - - An IS0 9001 : 2000 Certified Company

. - - --- - - - - Page 3

http://javabynataraj.blogspot.com

Page 90: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- .- .

By MI-. SomasekharReddy(Certified Professional) ' 1 -- -. - - - -. - .- A

I

1 All beans declared in this configuration file are default to 'all' dependency checking mode.

1 @Required Annotation In most scenarios, you just need to make sure a particular property has been set, but not all properties of a certain types I (primitive, collection or object). The @Required Annotation can enforce this checking,

I Spring dependency checking with @Required Annotation

I Spring's dependency checking in bean configuration file is used to make sure all properties of a certain types (primitive, 1 collection or object) have been set. In most scenarios, you just need to make sure a particular property has been set, but 1 not all properties..

I For this case, you need @Required annotation. I

-

Simply apply the @Required annotation will not enforce the property checking, you also need t o register an RequiredAnnotationBeanPostProcessor t o aware of the @Required annotation in bean configuration file. I

-

The RequiredAnnotationBeanPostProcessor can be enabled in two ways. I 1. Include <context:annotation-config /> 1

I 1 Add Spring context and ccontext:annotation-config /> in bean configuration file. I

2. Include RequiredAnnotationBeanPostProcessor

I I 1 Include 'RequiredAnnotationBeanPostProcessor' directly in bean configuration file.

http://www.springframework.org/schema/beans/spring-beans-2.5.x~d~~~ I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1

An I S 0 9001 : 2000 Certified Company - -. - - - - . .

Page 4 http://javabynataraj.blogspot.com

Page 91: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

( @Required example

1 Drivins.iava 1. package corn. neo . spring. bean ; 2. public class Driving {

1 3 . private String driver; 4. public void setDriver(String driver) {

1 5- this.driver = driver; 6. 1

( 7. public String gemriver ( ) {

8. return driver ;

1 9. 1

110. )

Car.iava 1. package com.neo.spring.bean; 2. import org.springframework.beans.factory.annotation.Re~ired; 3. public class Car {

4. private String breaks ; 5. private Driving driving; 6. @Required 7. public void setDriving(Driving driving) {

8. this.driving = driving; 9. 1 10. public void setBreaks(String breaks) {

11. this.breaks = breaks; 12. 1 13. public void drivecar ( ) {

14. System. ou t . println ("old man come across the road") ; 15. System. out .println (Ifapply breaksr1) ; 16. if (breaks !=null) {

17. System. ou t . println ("old man saved") ; 18. )else {

19. System. out .println ("old man kicked the bucket") ; 20. 1 21. if (driving. gemriver ( ) !=null) {

22. System. ou t . println (lldriver is drivingq1) ; 23. )else {

24. System. out .println ("owner is drivingf1) ; 25. 1 26. 1 27. 3

a~~licationContext.xml 1 . <?xml version="l. 0" en~oding=~UTF-8~~?> 2. <beans 3 . xmlns=lVhttp : //www . springf ramework . org/schema/beansl~

.Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad,'Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

I . ~ ... -- p a r

http://javabynataraj.blogspot.com

Page 92: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Spring-IOC Ry b k . SomasekharReddy(Certified Professional) ' \

<bean id=I1driveref class="com. neo . spring. bean. Drivingtt> <property name="drivertl ~a lue=~~dr iver"~ /proper ty> </bean> <bean id="carrefV class="~om.neo.spring.bean.Car~~ >

<property name="breakstl value="nice breakstt/> </bean>

</beans>

Client.iava 1. package com.neo.spring.client; 2. import org.springframework.context.App1icationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 4. import com.neo.spring.bean.Car; 5. public class Cllent {

6. private static Applicationcontext context=new 7 . ClassPathXmlApplicationContext( 8. ~corn/neo/spring/config/app~ication~ontext.xm~~~); 9. public static void main(String[] args) {

10. Car bean= (Car) context. getBean ( "carref") ; 11. bean. drivecar ( ) ;

12. 1 13. )

Output: org.springframework.beans.factory.~ean~nitializati~n~xcepti~n:

I NOTE: It is because driving property is unset. I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 I - - - . -

An I S 0 9001 : 2000 Certified Company -- A

Page 6 http://javabynataraj.blogspot.com

Page 93: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Bv Mr. SomasekharReddv[Certified Professioi?all

9 Auto wiring means automatically injecting the dependencies. 9 Instead of manually configuring the injection we done i t automatically by using auto wiring 9 To implement autowiring we use autowire attribute of <bean> tag.

There are five possible values to the autowire attribute of <bean >tag. 9 no 9 constructor 9 byName

~ Y T Y P ~ 9 autodetect

no: It won't allow autowiring.

byName: Mainly i t checks for 3 conditions if all these are valid then i t injects the values by setter approach. 1. Dependency bean name 2. Configured bean name 3. Setter method name

> I f dependency name is "abc", bean configuration should be "abc" and setter name method should be "setAbc(Abc abc)"

9 When i t finds 'autowire=byName' for any bean configuration, then it first checks for dependency bean name in the dependent bean, then it will checks weather any bean is configured in the in the spring configuration file with the same name. I f it finds then i t will call corresponding setter method of the dependent bean.

Note: It doesn't bother about the argument types, it only bothers the names because it is autowiring 1 byName.

" " b ' iii~ yw byname . ,

!:I. ;,.+ ; ..I src

Auto wirina bvName

. . .

i i ; @,.-a com.neo.spring.bean i i i &{ -@ Service,java i : i . . . . . . . , . . . . . , <

El . @ Servlet. java ! . : , E cum.neo,spring.client : : : . . . , . . . ;+;., @ [rlient,java . . . ! !

, i . . i . E -fB com.neo.spring.config . , . . . . . . . . I .*::7 . . . . . . .

; ; applicationContext,xml j W-.& JRE System Library [JAVA] .i &...a Spring 2,s Core Libraries

Service.iava 1. package com.neo.spring.bean; 2. public class Service {

3. public void serviceMethod ( ) {

4 . System. out. println ("Service. serviceMethod ( ) called") ; 5 . 1 6 . 1

I Servlet.iava

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

L An IS0 9001 : 2000 Certified Company -- . - -. - -- -

P a g T http://javabynataraj.blogspot.com

Page 94: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

~ ~~~ . -~

Spring-IOC .- ... . . By Mr. ~ o m a s e k h a r ~ e d d ~ ( ~ e r t i f i e d Professional) 'L i

1. package com.neo.spring.bean; 2. public class Servlet { ,

3. private Service service; 4. public void setservice (Service service) {

5. this.service = service; 6. System.out.println("injection happened"); 7. 1 8. public void servletMethod ( ) {

9. System. out. println ("Servlet. servletMethod ( ) calledff) ;

10. service.serviceMethod(); 11. 1 12. 1

Client.iava 1. package com . neo . spring. client; 2. import org.springframework.context.App1icationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 4. 5. import com.neo.spring.bean.Serv1et; 6. public class Client {

7 . private static Applicationcontext context=new 8. ClassPathXmlApplicationContext( 9. f1com/neo/spring/config/applicationContext.xmlff); 10. public static void main (String[] args) {

11. Servlet servlet= (Servlet) context. getBean (flservletref Iv) ; 12. servlet . servletMethod ( ) ;

13. 14. )

O U ~ D U ~ injection happened Servlet . servletMethod ( ) called Service. serviceMethod ( ) called

Auto wirina ( b v T v ~ e l byType mainly i t checks for 3 conditions. if all these are valid then it injects the values by setter approach.

1. Dependency bean Type 2. Configured bean Type 3. Setter method Argument Type

I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 1 .- . -- - - - - - - - I

An IS0 9001 : 2000 Certified Company Page 2

http://javabynataraj.blogspot.com

Page 95: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - - - - - - -- - ---

Spring- IOC By Mr. SomaseltharReddy(Certified Professional)

I > When it finds 'autowire=byTypef for any bean configuration, then i t first checks for dependency

bean Type in the dependent bean, then i t will checks the spring configuration file, weather any bean is configured with the dependency type, i f i t finds it will check for any setter method tha t

I takes bean dependency type as an argument, if i t finds, then it will call that setter method.

Note: it doesn't bother about the setter method names, i t only bothers the Types. I -

I autowirinq b v T v ~ e

1 .+. & bytype : s r i i : . . ~:or~-l, rleo, spring.hearl 1 ; ; ; , .

. +.., . . . $ + ; j q .=- , . . -#ar-n:.ice. java : : : '

i%j . & 5er,,:*let, java I . / : ! . ,-p*

. . 0 . g:f corn, rlec~. spring, client . ...

[%! i 41 cIlierlt, java I : . ; {=; r- p-. " I I -. LG::. cor~i, r~eo. spring .cor~Fig . . . . . . a :

t. -' spplicationCuntext .xml i$& JRE system Library [JAVA]

: : i 33 .-.aL Spring 2.5 Core Libraries / i_

-

I Service.iava 1. package com.neo.spring.bean;

1 2. public class Service (

3. public vold serviceMethod () (

4 . System. o u t . println ("Service. serviceMethod () calledw) ; 1 5. 1

I 6. 1

I Servlet. iava I 1. package com.neo.sprlng.bean; 2. public class Servlet {

3. private Service servicel; I 4. public void setService3(Service service) {

5. this.service = service;

1 6 - System. o u t .println (Ifin jection happened") ; 7 . 1 8. public void servletMethod() {

System. o u t . println ("Servlet . servletMethod () calledn) ; 10. service. serviceMethod () ; I 11. 1 12. 1

I

I - - a~~licationContext.xmI

1. <?ml version="l. 0" encoding="UTF-8"?> I 2 . <beans

3 . xmln~="http://www.springframework.org/schema/beans~~

1 4 . xmln~:xsi="http://www.w3.org/2OO1/XMLSchema-instance~~ 5 . xsi:schemaLocation=whttp://www.springfraework.org~schema/beans 1 6. http: //WWW. springframework. org/schema/beans/spring-beans-2 .5. xsdIr> 7 .

i - Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842

I

. .. An IS0 9001 : 2000 Certified Company

-- -. - - - - - - -- Page 3

http://javabynataraj.blogspot.com

Page 96: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

spring-IOC By Mr. ~ o m a s e l t h a r ~ e d d ~ f ~ e r t i f i e d ~rofessional)

Client.iava 1. package com.neo.spring.client; 2. import crg.springframework.context.ApplicationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 4. import com.neo.spring.bean.Serv1et; 5. public class Client {

6. private static Applicationcontext context=new 7. ClassPathXmlApplicationContext ( 8. "com/neo/spring/config/applicationContext.xmltt); 9. public statlc void main (String [ I args) {

10. Servlet servlet= (Servlet) context. getBean ( "servletref ") ; 11. servlet.servletMethod(); 12. I 13. 1

O U ~ D U ~ I I

injection happened -

Servlet . servletMethod ( ) called Service. serviceMethod ( ) called I

--

Auto wirina (constructor) I constructor mainly i t checks for 3 conditions. i f all these are valid then i t injects the values by constructor approach.

Dependency bean Type Configured bean Type

I Constructor Argument Type 1

P When it finds 'autowire= constructor' for any bean configuration, then it first checks for dependency bean Type in the dependent bean, then i t will checks the spring configuration file,

I weather any bean is configured with the dependency type, if it finds i t will check for constructor I which will takes dependency type as an argument. I f it then i t will call the corresponding I

constructor. I

Note: It won't bather about dependency name. It bathers about only dependency type, constructor argument type. I

@.-@ cam .neo.sprinq. hean . . i 8.. f& Service. java , 7 (3 ., Servlet, jma

&-@ com .neo,spring.client . . i a-,- @ Client, java

~om,neo,spring~config

'-. ,.&,:; applicationcontext .xml

Service.iava 1. package corn.neo.spring.bean; 2. public class Service {

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I - - - - - --- --- An IS0 9001 : 2000 Certified Company .-

Page 4 http://javabynataraj.blogspot.com

Page 97: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- ..- -- ---

Spring-IOC By Mr. SomasekharReddy(Certified Professional) r ----. .- ..-.-........-..-..-ppp--.- . . . . , . . ... . . , , .......... . . . .. .....

3. public void serviceMethod ( ) {

1 4 . System. out .println (llService. serviceMethod ( ) calledf1) ; 5 . 1

1 6. 1

Servlet.iava ) 1 . package corn. neo . spring. bean ; 2. public class Servlet {

private Servlce servlcel; public Servlet (Service service) {

th~s.service=service; System. out .println (I1Servlet constructor") ;

1 public vold servletMethod(){

System. out .println (I1Servlet . servletMethod() calledn) ; service.serviceMethod();

1 1

a~~licationContext.xmI 1 1. <?xml version="l. 0" en~oding=~~UTF-B~~?>

-- 2. <beans 1 3. xmlns="http : //www . springframework. org/schema/beans"

4 . xmlns:xsi="http://www.w3.org/2001/XM~Schema-instance~~

1 5 - xsi:schemaLocation="http://www.springframework.org/schema/beans 1 6. http: //www . springframework. org/schema/beans/spring-beans-2.5. xsdv>

7.

1 8. <bean id="service" cla~s=~~com. neo . spring. bean. Serviceq1/>

I Client.iava 1. package com.neo.spring.client;

1 2. import org.springframework.context.App1i~ationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 4. import com.neo.spring.bean.Serv1et; 1 5. public class Client {

6. private static Applicationcontext contexenew 1 7. ClassPathXmlApplicationContext( 8. "com/neo/spring/conf ig/applicationContext . xml") ;

( 9. public static void main(String[] args) {

' 10. Servlet servlet= (Servlet) context. getBean (I1servletref ") ; 11. servlet . servletMethod () ;

I 12. 13. }

- - O U ~ D U ~ Servlet constructor 1 Servlet . servletMethod ( ) called Service. serviceklethod ( ) called

Auto wirinq (autodetect1

1 autodetect Chooses "constructor" or "byTypel' through introspection of the bean class. If a default constructor is found, "byType" gets applied. If not found it will apply 'constructor'.

I -- Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

I An I S 0 9001 : 2000 Certified Company -- - . -~ -

. ~

Page 5 http://javabynataraj.blogspot.com

Page 98: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

By Mr. Somaselthal-Reddy(Certified ~ ro fess iona l ) 1:

Service.iava 1. package com.neo.spring.bean; 2. public class Service {

3. public void serviceMethod0 { .4. System. out .println (llService 5. 1

serviceMethod ( ) called") ;

Servlet.iava 1. package com . neo . spring. bean ; 2. public class Servlet {

3. private Service service; 4. public Servlet (Service service) {

5. this.service=service; 6. System. out. println ( "Servlet constructorf1) ;

7. 1 8. public void setservice (Service service) {

9. thls.servlce = service; 10. System. out .println ("setter method") ; 11. 1 12. public void servletMethod () {

13. Sys tem. out .println ( IrServlet . servletMethod ( ) called") ; 14. service.serviceMethod(); 15. 1 16. )

Client.iava 1. package com.neo.spring.client; 2. import org.springframework.context.App1icationContext; 3. import org.springframework.context.support.ClassPathXmlApplicationContext; 4. import com.neo.spring.bean.Servlet; 5. public class Client {

6. private static Applicationcontext context=new 7 . ClassPatN(mlApplicationContext( 8. 11com/neo/spring/config/app~icationContext.xm~11);

1 9. public static void main(String[] args) {

10. Servlet servlet= (Servlet) context. getBean (I1servletref ") ; 11. servlet . servletMethod () ;

12. 1 13. 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

--- -- -- - - -- - -- - - - -. - - - - An I S 0 9001 : 2000 Certified Company Page 6

http://javabynataraj.blogspot.com

Page 99: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

1 ou tpu t Servlet constructor 1 Servlet. servletMethod ( ) called Service. serviceMethod ( ) called

I 1 Observe above application we provided both constructor and setter in Servlet.java but i t injects by

constructor approach because there is no default constructor. I

I Now provide default constructor also in Servlet.java and run the application. 1 Servlet.iava 1 . package com. neo . spring. bean; 2. public class Servlet {

3 . private Service service ; 4. publicServlet() {

5. System. ou t . println (I1def ault constructor") ; 6. 1 7 . public Servlet (Service service) {

8. this.service=service; 9. System. out .println (flServlet constructorf1) ; 10. 1 11. public void setservice (Service service) {

12. this.service = service; 13. System. out .println ("setter methodf1) ; 14. 1 15. public void servletMethod() { 16. System. out . println ("Servlet. servletMethod () calledfq) ; 17. service.serviceMethod() ; 18. 1 19. }

setter method Servlet .servletMethod() called

1 Service. serviceMethod ( ) called

( Now observe here injection is happened by using byType because default constructor is there.

Note: It's always good to combine both 'aut ndency-check' together, to make sure the property is always auto-wire successfully.

Spring 'auto-wiring' make development faster with great costs - it added complexity for the entire bean configuration file, and you don't even know which bean will auto wired in which bean.

In practice, i rather wire it manually, it is always clean and work perfectly, or better uses @Autowired annotation, which is more flexible and recommended.

. -.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

. . ~ . . -- Page 7

http://javabynataraj.blogspot.com

Page 100: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

---. . - - . . . . - ~ - - . - ~ - p ~ p ~ ~

7 By Mr. Somasel:harReddy(Certified Professional) , -. i

Spring Auto-Wiring Beans with @Autowired annotation

I In last Sprinq auto-wirins in XML example, it will autowired the matched property of any bean in current Spring container. In most cases, you may need autowired property in a particular bean only. 1 In Spring, you can use @Autowired annotation to auto wire bean on the setter method, constructor or a field. I

Moreover, it can autowired property in a particular bean. 1 <.

I Note 1 The @Autowired annotation is auto wire the bean by matching data type.

I I

1 See following full example to demonstrate the use of @Autowired. , 1

package com.neo.spring.bean; I I public class Customer I I

/ / y o u want a u t o w i r e d t h i s f i e l d . private Person person;

private i n t type; private String action;

/ / g e t t e r and s e t t e r m e t h o d

I </beans>

2. Register AutowiredAnnotationBeanPostProcessor

To enable @Autowired, you have to register '~utowiredAnnotationBeanPostProcessor', and you can do it in two ways : : i I 1. Include <context:annotation-config b l Add Spring context and <context:annotation-config I> in bean configuration file. - 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- -- - - . -- - - An I S 0 9001 : 2000 Certified Company

- - - - - - - - --

Page 8 http://javabynataraj.blogspot.com

Page 101: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

! </beans>

I Full example,

a e a n id="PersonBean" class="com.neo.spring.bean.Person"> <property name="nameU value="neo" /> <property name="address" value="address ABC" /> <property name="agen value="29" />

</bean>

</beans>

2. Include Auto wiredAnnotationBean PostProcessor

Include 'AutowiredAnnotationBeanPostProcessor1 directly in bean configuration file.

<bean id="PersonBeanW class="com.neo.spring.bean.Person"> <property nane="name" value="neo" /> <property name="address" value="address ABC" /> <property name="ageU value="29" />

</bean>

</beans>

3. mutowired Examples

Now, you can autowired bean via @Autowired, and it can be applied on setter method, constructor or a field.

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

. . - -- -. . - - - - - - - . - - - - - . - - - -. An IS0 9001 : 2000 Certified Company p a s

http://javabynataraj.blogspot.com

Page 102: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - -. - . - . . - . . - - -- -

S ~ I . ~ I I , O - I O C By M r . s ornayekhar~eddy(~ertified P r o Fessional) ,

i 1 I . @Autowired setter method I

package com.neo.spring.bean;

I import org.springframework.spring.beans.factory.annotation.Autowired;

1 public class Customer

private Person person; I private int type;

private String action; //getter and setter methods

1 @Autowired - 1 public void setPerson(Person person) { I

I this.person = person; 1

1 2. @Autowired construtor package com.neo.spring.bean;

import org.springframework.spring.beans.factory.annotation.Autowired;

public class Customer (

private Person person; private int type; private Strlng action; //getter and setter methods

@Autowired public Customer(Person person) {

this.person = person; I

1 3. @Autowired field 1 package com.neo.spring.bean;

import org.springframework.spring.beans.factory.annotation.Autowired; I public class Customer

@Autowired private Person person; private int type; private String action; //getter and setter methods

I

The above example will autowired 'PersonBean' into Customer's person property.

package com.neo.spring.bean; I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

An IS0 9001 : 2000 Certified Company -- - -. -- . -- - - -. -

Page 10 http://javabynataraj.blogspot.com

Page 103: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

By Mr. SomasekharReddy(Certified Professional] 1 I

import org.springframework.context.ApplicationContext; ( import org. springframework. context. support .ClassPathXm1App1icationContent;

1 public class App I I , public s t a t i c void main( String[] args ) I I I

Applicationcontext context =

new ClassPathXmlApplicationContext(new String[] ("SpringBeans.xrn1" j);

Customer cust = (Customer) context. getBean ("CustomerBean") ; System.out.println(cust);

I ( I output

Customer [action=buy, type=l, person=Person [address=address 123, age=28, narne=neo]]

I

I I Dependency checking

/ I package corn. neo . spring. bean; I

-1 By default, the @Autowired will pelform the dependency checking to make sure the property has been wired

-

I @Autowired(required=false) private Person person; private in t type; private String action; / / g e t t e r and s e t t e r methods

1 In the above example, if the Spring can't find a matching bean, it will leave the person property unset

properly. When Spring can't find a matching bean to wire, it will throw an exception. To fix it, you can disable this checking feature by setting the "required" attribute of @Autowired to false.

I public c lass Customer '

The @Qualifier annotation us used to control which bean should be autowire on a field. For example, bean configuration file with two similar person beans.

I

<context: annotation-conf ig />

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666, 23734842 An I S 0 9001 : 2000 Certified Com~anv

- -- -- - . -- - - .- -- - . ,

Page 17- http://javabynataraj.blogspot.com

Page 104: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

I Spring-IOC I

- -. By Mr. SomasekharReddy(Certified ~rofessiona1)- 1

I I -.\ I

Will Spring know which bean should wire?

To fix it, you can use @Qualifier to auto wire a particular bean, for example,

package com.neo.spring.bean;

import org.springframework.spring.beans.factory.annotation.Autowired; import org.springframework.spring.beans.factory.annotation.Qua1ifier;

public class Customer {

@Aut owired @Qualifier ( "PersonBeanl") private Person person; private int type ; private String action; / / ge t t e r and s e t t e r methods

1

! I It means, bean "PersonBeanl" is autowired into the Customer's person property. Read this full example - Spring ',

I Autowirinn @Qualifier example i I

Conclusion 1 This @Autowired annotation is highly flexible and powerful, and definitely better than "autowire" attribute in bean configuration file. 1

I Naresh i Technologies, Opp. Satyam 'Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

An IS0 9001 : 2000 Certified Company - - - -- - - - - - -- - - -. .- --

i Page 12

j http://javabynataraj.blogspot.com

Page 105: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

PropertvEditor 1

I P PropertyEditor object is used to convert String representation of data into Object representation and ,

vice versa. 1 P PropertyEditor is an interface that belongs to java bean API I

I Benefits of propertv editors in sprinq: I !

I f we use property editors in spring, we get the flexib~lity in populating the bean fields directly with string ' type even though bean fields are of some object type. I I Built-in sprinq framework propertv editors: 1

ByteArrayPropertyEditor, ClassEditor, CustomBooleanEditor, LocaleEditor, URLEditor, FileEditor, CustomCollectionEditor ... etc like this we have so many built-in property editors are there. These all are used by spring framework internally.

I

Custom Property editor: Custom Property ed~tor means our own property editor class used to perform our own application specific conversations.

Steu 2: - I Develop the custom property editor class by extending java.beans.PropertyEditorSupport class. I n our ( project the editor bean is ContactNurnberEditor.java

-

Note: Custom property editor class name should be suffixed with Editor to the dependency bean class and should be placed in the same package where dependency bean resides. I f we do so we no need to perform 4th step.

Steus to develop custom pro~ertv editor: Steu 1: develop a spring bean (dependency bean) whose values are populated from String representation t o object representation. I n our project the dependency bean is ContactNumber.java

S t e ~ 3 : Override setAsText(String value) method in the custom property editor class and implement convertion code(String to required object). After conversion call setValue(converted0bject) method.

S t e ~ 4 : Configure the custom property editor in the configuration file (applicationContext.xml) by configuring the class org.springframework. beans.factory.config.CustomEditorConfigurer with property name="customEditors".

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

- An IS0 9001 : 2000 Certified Company -- - . - - . - Page 1

http://javabynataraj.blogspot.com

Page 106: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

. -- --

Spring-IOC By Mr. ~omasekhar~edd~(Certified ~ r o f e s s i o n m

Project on s~rincr Custom Pro~ertvEditors:

~ustmwpropert~~rditcr

d bF9 STC

r @ curn .ne~ . rp r~ t i ~ l . c I~en t

2 Kj Clictit, ja~.~a

4 @ curn.nea.spr~ng.cunf~g

appl~cat~cl-~C~;t-j te,t,xml

> JRE !$stmi L~bl-ail , & Spr~ng 2.5 Cc re L ~ b t a l - i f

ContactNum ber.iava 1. package com.neo.sprlng.bean: 2. 3. public class ContactNumber {

4. private String countrycode; 5. private String stdCode; 6 . private String actualNumber ; 7. 8. public ContactNumber(String countrycode, String stdCode, String 9. actualNumber) {

10. this.countryCode = countrycode; 11. this.stdCode = stdCode; 12. this.actualNumber = actualNumber; 13. 1 14. 15. 16. public String getContactNumber() {

17. return countrycode + 1'-11 + stdCode + 1'-11 + actualNumber; 18. 1 19. )

ContactNumberEditor.iava 1 . package corn. neo . spring. bean ; 2. 3. import java.beans.PropertyEditorSupport; 4. 5. public class ContactNumberEditor extends PropertyEditorsupport {

6. @Override 7. // container will pass injected contact number as a string 8. public void setAsText (String text) throws IllegalArgumentException { ,

9. 10. String[] token = text. split (I1-11) ; 11. ContactNumber contactNher = new ContactNumber (token LO] , 12. token [1] , token [2] ) ; 13. 14. setvalue (contactNumber) ; 15. 1

- - - - -

Naresh i Technologies, Opp. Satyam Theatre, Arneerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

i

-. . - - - - -- - - Page Z

http://javabynataraj.blogspot.com

Page 107: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

public void setContactNumber(ContactNumber contactNumber) {

this.contactNumber = contactNumber; 1

1 . package corn. neo . spring. bean ; I Emu'ovee~iava

3. publlc class Employee {

4 . private~nteno; 5 . private S trlng ename ; 6. private String city; 7. private ContactNumber contactNumber; 8. 9. public void setEno(int eno) {

10. thls.eno = eno; 11. 1 12. 13. publ~c void setEname (String ename) {

14. this.ename = ename; 1 15. 1

public void displayDetails ( ) {

System. out .println (eno) ; System. out. println (ename) ; System. out .println (city) ; System.out.println(contactNumber.getContactNumber());

1

-

auulicationContext,xml 1 . <?xml version= "1.0 " encoding= "UTF-8 "?> 2. <beans 3 . xmlns= "h t tp : //m. springframework. org/schema/beans " 4 . xmlns : xsi= "ht tp: / /www. w3. org/2001/XMLSchema-instance " 5 . xmlns : p= "h t tp: //www. springframework. org/schema/p" 6 . xsi:schema~ocation="http://ww.springframework.org/schema/beans 7 . http : //www. springframework. org/schema/beans/spring-beans-2.5. xsdm> 8. 9. <bean id="erqpU class= "corn. neo. spring. bean .Employeev > 10. <property name= "eno " value= "1 001 " property> 11. <property name= "ename " value= "sekhar" property> 12. <property name= "ci tyl' value= "Hyderabad" property> 13. <property name= "con tactNumber " value= "91 -084984-232236" > 1 4 . </property> 1 5 . </bean> 16. 1 7 . <bean class= "org. springframework. beans. factory. config 18. . Cus tomEdi torconfigurer " > 19.

16. 17. public void setcity (String city) {

18. this . city = city ; 19. 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company

- - - - - - . - --- - - . . Page 3

http://javabynataraj.blogspot.com

Page 108: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

<property name= "customEdi tors "> <map>

<entry key= "corn. neo. spring. bean. ContactNumberf' > <bean class="corn.neo.spring.bean.ContactNumberEditor" > </bean>

</entry> </map>

</property>

Client.iava 1. package com.neo.spring.client; 2. import org.springfranework.context.ApplicationContext; 3. import org.springframework.context.support.C1assPathXmlApplicationContext; 4. 5. import com.neo.spring.bean.Emp1oyee; 6. public class Client {

7. private static AppllcationContext context = new 8. ClassPathXmlApplicationContext( 9. "com/neo/spring/config/applicationConte~t.xml~~); 10. 11. public static void main(String[] args) {

12. Emplcyee employee = (Employee) context. getBean (I1empf1) ;

13. employee.displayDetails(); 14. 1 15. )

Ouput 1001 sekhar Hyderabad 91-084984-232236

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842

-- An I S 0 9001 : 2000 Certified Company ..-- .. . .. . - --.pp.-pp-- ... -- -

Page 4- http://javabynataraj.blogspot.com

Page 109: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

I I Spring-IOC By Mr. Sornasel<harReddy(Certified Professional)

i Internationalization(Il8N) 3 I n software system Internationalization means based on the users country and language we need

to display respective content in the browser. I > I n JAVA in order to get the user country and language we can achieve by using java.util.Locale

I object.

A java.util.Locale is a lightweight object that contains only a few important members: • A language code

I • An optional country or region code

I w An optional variant (in IIVDIA i t is called as State) code

1 The notation of Locale:

/ < language code>[ -<country code>[ -<variant code> ] 1 In the above notation each code is separated with an underscore symbol (-). The country code and variant codes are optional.

I Lanauaae codes: Language codes are defined by I S 0 639 that assigns two- and three-letter codes to most languages of the world. Locale uses the two-letter codes to identify the target language.

Language Code Examples in ' the I S 0 639 Standard ..........................................................

: -Language .......................................................

Arabic - "" ..... - 'German

---"---. -- Spanish Es

Countrv (Reaion) Codes: Country codes are defined by I S 0 3166, another international standard. It defines two- and three-letter abbreviations for each country or major region in the world. I n contrast to the language codes, country codes are set uppercase.

Table 3. Some Country Codes Defiiled in the I S 0 3166

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

- - -- - - - - - - - - - - - Page 1

http://javabynataraj.blogspot.com

Page 110: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

~

Spring-IOC By Mr. ~ o m a s e l < h ~ r ~ e d d ~ ( ~ e r t i f i e d ~rofessional)!-?I

-. Variant (State) Code: To provide additional functionality or customization we use Variant code, that isn't possible with just a , language and country. Ex: de-DE------------------3 German-speaking German locale

de-DE-EURO------------3 German-speaking German locale with a euro variant en-US-S~liconValley-----3 English speaking US locale for silicon valley people -

In Java the syntax of above notation by three constructors: Locale (String language)

Locale (String language, String country) Locale (String language, String country, String variant)

ExamDle on the above notations: // Creates a generic English-speaking locale.

Locale localel = new Locale("en"); // Creates an English-speaking, Canadian locale. Locale locale2 = new Locale("en", "CAN); // Create a very specific English-speaking, U.S. locale for Silicon Valley. Locale locale3 = new Locale("en", "US", "SiliconValley");

STEPS to write I18N application in s~rincr: In three steps we can create 118N application. Steul: Create the required properties flles.

Syntax for naming the properties file: We can write this in three ways.

1. Propertiesfilename~languagecode.properties 2. Propertiesfilename~languagecode~countrycode.properties 3. Propertiesfilename~languagecode~countrycode~varientcode.properties

Our ~roiect ~rouertv files: I n this we have created four properties files. The properties file should be in the form of key and value pair. I n our properties files the key is 'welcome. message'.

1 .A~~licationResources en US SiliconVallev.~roDerties welcome.message=welcome t o US silican vally english users {0).{1) note: (O),(l)bused t o pass some values dynamically, called as place holders

2.A~~licationResources fr CA.~ro~erties welcome.message=welcome t o french CANADA english users

3.A~u~icationResources zh CN.~rouerties welcome.rnessage=welcome t o chineese english users

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company - - . - - - - - . -

Page 2 http://javabynataraj.blogspot.com

Page 111: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

I 4.ApplicationResources.~ro~erties I I welcome.message=welcome to users I

I I I Note: in the above properties file we didn't mention any language code and country code this will execute

1 by default if it doesn't find any codes. I

Configure the properties files in the configuration f~le. I Step 2: 1 > Inject the properties file prefix to spring provided bean "ResourceBundleMessageSourcef' using I 'basename' or 'basenames' values for the name attribute of <bean> tag and also the id

reference for this bean should be 'messagesource'. i I f we are injecting one properties file then we can use 'basename 'or 'basenames' value for the

name attribute without <list> tag. h I n case if we are injecting more than one properties file then we should use only 'basenames' value

for the name attribute with <list> tag.

Client urosram: Here to get the language content we should call getMessage(key, arguments, locale) method of Applicationcontext of by passing

1. Key 2. Arguments to the message 3. Locale Object

In Our project : Key---------------------+ welcome.message

Messege arguments---+dynamic values for the place holders i.e., (O)( l ) Note:if we don't have any arguments then we should pass null as an argument

A @ corn,tieo,spr~nq,cl~etit

2) Client.java

re a com.t i~o,~pr~ng,conf ig F:p apphcationCant&.xrnl

r @ rom.nro.sprrtig.piops

ApplicatianRcsource~5ennUS55iti~~nVaflyYpr~perti~~

App5cat1onRe~ourcrr-fr-CA,pr~pe&5e-~ ApplicationEes-ourc~-~h~CilJ,p~(rperfie~

' Applrcat~otiRerourc~s~p~operties

r. & IRE Systmm Libl-a1.4. ; ., .>- .. c"

& Sprit~g 2.5 Core Libraries

Client.iava: 1. package com.neo.spring.client; 2. import java.util.Locale; 3. import org.springframework.context.App1icationContext; 4. import org.springframework.context.support.ClassPathXmlApplicationContext; 5. public class Client {

6. private static Applicationcontext context = new 7. ClassPathXmlApplicationContext (

- - - - - - - -- - - - - -- - - - - -- - - - - - -- -- .

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company - -- - -. - - -. . - -. . . . . . . . . . - - . - . - - . . -- -, . - .- - --

~agT3- http://javabynataraj.blogspot.com

Page 112: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- - -. -- -. -- - -. - .

S p r i n g - l O c -- By Mr. SomaseltharReddy(Certified - -. - - - ~ r o f e ? s i o n a v ' . . . . . . . .- . . . .. .. - . . . . . . . . .. .. .. - .. . . . .

- , . - 1, 8. 11com/neo/spring/config/app~icationContext.xml"); 9. public static void main(String[] args) { - 1

1 10. String message = context.getMessage(flwelcome.messagell, new 11. Object [ I { llUS1l, "English" } , new Locale (ffenll, "US", 12. llSiliconValleyll) ) ;

System.out.println(message); I

13. 14. message = context.getMessage('lwelcome.messageff, null, new 1

x.

15. Locale (flzhll, T N " ) ) ;

16. System. out. println (message) ; 17. message = context.getMessage(

I' -, 18. "welcome. message", null, new Locale ("Arl') ) ; 19. System. out .println (message) ; 1 . 20. 1 21. } I auulicationContext.xml 1 . <?xml version= "2.0 " encoding= "UTF-8"? > 2 . <beans xmlns= "ht tp : //m. springframework. orq/schema/beans " 3 . xmlns : xsi= "ht tp: //m. w3. org/200l/~~~~chema--instance " 4 . xmlns : p= "h t tp : //www. springframework. org/schema/p " 5. xsi:schemaLocation="http://m.springframework.org/schema/beans 6 . h t tp : //www. springframework. org/schema/beans/spring-beans -2.5. xsd "> 7 . <bean id= "messageSource " class= "org. springframework. context. support 8. , ResourceBundl eMessageSource "> 9. <property name= "basename " 10. value= "com/neo/spring/props/~pplica tionResources "> 11. </property> 12. </bean> 13. </beans>

AuulicationResources en US SiliconVallev.urouerties 1. Welcome.message=This is the {O){1) welcome message

AuulicationResources fr CA.urouerties: 1. Welcome.message='llhis is the Canadian French welcome message

AuulicationResources zh CN.urouerties: 1. Welcome.message=~is is the Chinese welcome message

AuulicationResources. Prouerties: 1. Welcome.message=This is the default message

Outuut This is the US English welcome message This is the chinees welcome message This is the default message

I

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

- - - - - .- -. - .- - - 2 Page 4

http://javabynataraj.blogspot.com

Page 113: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

-- - -- - - - - - - --

Spring-IOC By Mr. SomasekharReddy(Ce'rtified Professional)

1 Q.)How to work with multiple spring configuration files? When the spring configuration file size is huge, i t is difficult to maintain, so in that scenarios w e

j generally have multiple configuration files. e We can work w ~ t h multiple spring configuration files in two ways

l o By importing other spring file into the current configuration file.

Ex: <import resource="other-spring-beans.xmIm/ > o By passing all spring bean configuration files as a string array t o the constructor of the

1 container 1 new ClassPathXmlApplicationContext(new String[] {"beans-

1 l .xml", "beans-Z.xml.xml","beans-3.xml"));

I Multiconfiql

'& rnult ico-nfiyl && src

e2 c o n 7 . n ~ 0 . ~ - ~ 1 - i t > g . b ~ a t - 1

I :J 1 Col-~tr-c;ller-,i a ~ a I

. - Dao. java

i $;CJ Str+.:i c E.J a-'v.a

Controller.iava 1 . package com . neo . spring. bean; 2. 3. public class Controller {

4. private Service service; 5. 6. public void setservice (Service service) {

7 . this.service = service; 8. 1 9. 10. public void controllerMethod() {

11. System. out .println ("Controller. controllerMethod () ") ;

12. service. serviceMethod 0 ; 13. 1 14. 1

Dao.iava 1. package com.neo.spring.bean; 2. 3. public class Dao { 4 . public void daoMethod ( ) {

5. System. out .println("Dao .daoMethod() ") ; 6 . 1 7 . 1

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company

- - - - . - - -. - . . - . . . --

Page 1 http://javabynataraj.blogspot.com

Page 114: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- .. - - - - - -- . - - i Spring-IOC By M r . SomasekharReddy(Certified Professional) . . . . . . . . . . . . . . .. . . .- .

..... -. . -,i I

. . . . - , . . -.-.- I _I

Service.iava 1. package com . neo . spring. bean ; 2. 3. public class Service {

4 . private Dao dao; 5. 6. public void setDao (Dao dao) {

7. this.dao = dao; 8. 1 9. 10. public void serviceMethod() {

11. System. out. println (I1Service. serviceMethod ( ) I f ) ;

12. dao. daoMethod ( ) ;

13. 1 i4. 1

Client.iava - 1 . package corn. neo . spring. client; 2. 3. import org.springframework.context.ApplicationContext; 4 . import org.springframework.context.support.ClassPathXmlApplicationContext; 5. 6. import com.neo.spring.bean.Controller; 7. 8. public zlass Client {

9. private static Applicationcontext context = new 10. ClassPathXmlApplicationContext( 11. ncom/neo/spring/config/spring-controller-config.ml~1); 12. 13. public static vod main(String[] args) {

14. Controller controller = (Controller) 15. context.getBean("controllerref"); 16. controller.controllerMethod(); 17. 1 18. 1

s~rina-controller-confia.xml 1 . <?xml version= "1.0" encoding= rrUTF-8v?> 2. <beans xmlns="http://www.springframework.org/schema/beans" 3 . xmlns : xsi= "ht tp: //www. w3. org/2001/~~~~chema-instance " 4 . xmlns : p= "h t tp : //www. springframework. org/schema/p " 5 . xsi : schemalocation= "http: //www. spr-ingframework . org/schema/beans 6 . http : //www. springframework. org/schema/beans/spring-beans-2.5. xsd "> 7 . <import resource= "spring-service-config. x u 2 " /> 8 . <bean id= "con trollerref" class= "corn. neo. spring. bean. Con trolleru> 9 . <property name= "service " ref = "serviceref" X/property> 10. </bean> 11. </beans>

s~rine-dao-confia.xml 1 . <?ml version= "1.0" encoding= "UTF-a"?> 2 . <beans xmlns= "ht tp : //www. springframework. org/schema/beans " 3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 . xmlns : p= "h t tp : //www . springframework. org/schema/p " 5 . xsi : schemalocation= "h t tp: //www. springframework. org/schema/beans

I, Naresh i Technologies, Opp. satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

~- ... - -- - Page 2

http://javabynataraj.blogspot.com

Page 115: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

- - - - - - . . -

p d L - z - - - -

By Mr. SomasekharReddy(Certified Professional) 1

6. ht tp : //www. springframework. org/schema/beans/spring-beans-2.5. xsd '> 7. <bean id= "daoref " class= "corn. neo . spring. bean. Dao "> R. </bean> 9. </beans>

s~rins-service-confiq.xm I 1. <?xu11 version= "1.0" encoding="UTF-8"?> 2 . <beans xmlns= "h t tp : //www. springframework. org/schema/beans "

i 3. xnllns: xsi= "http://www. w3. org/2001/XMLSchema-instance" xrnlns : p= "h ttp : //:nv. springframework. org/schema/p" xsi:schemaLocation="http://m.springframework.org/schema/b~ans ht tp : //www . springframework. org/schema/beans/spring-beans-2.5. xsd ">

<import resonrce= "spring-dao-config.dU /> - <bean id= "serviceref" class= "corn. neo . spring. bean. Service ">

<property name= "dao " ref= "daorefV property> </bean>

</beans>

I

I Outuut I Controller. controllerMethod ()

Service. serviceMethod ( ) Dao . daoMethod ( )

Multiconfiq2 dl $sc t-r-iuJti~~l~r~figZ

A &@ src s $3 ~ ~ n l . n ~ c . ~ p l ~ i l l g . b ~ a ~ ?

. . . . . . . . ! . t i ......... < I ~ ~ ? t t - ~ : l I r ~ - . j a . . . . . a ....

, .f ' i L ........ - CJac.ja.,.-a ....

... LF.3 Sel-./i 8: c.j a,..a

a @ cwm.neo.~p.r-ing.client 5 32 Ciictit.java

d +& ca.m.nec.spr-ing.co:t~fiy &-i;: spring - ro.ntro.ll el-- ,: 0 nfi g:.xm.1. * ' :

. spring-clau--c.anfig.xtnI: .:..

,b:::~ zprin g - 5 el-vice- c ~ . n f ig . x n ~ l :. &I?, JEES.i.'st-t,-,, L i l : > r . ~ l y f i - , . .i:;:-.: ...: c;:

:. . me. Sprinq 2.5 cIc1.e L i t>r..r.ic.a

Contrsl ler. iava 1. package com.neo.spring.bean; 2. 3. public class Controller (

4. private Senrice service; 5. 6. publlc void setServiceIService service) {

7. this.service = service; 8. 1 9. 10. public void controllerMethod () {

11. System. out. println ("Controller 12. sen-lce . serviceMethod() ;

.ILI

I Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An IS0 9001 : 2000 Certified Company

. ...................... ................

Page

http://javabynataraj.blogspot.com

Page 116: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

Dao.iava 1 . package com . neo . spring. bean ; 2. 3. public class Dao (

4 . public void daoMethod ( ) I 5 . System. out. println ("Dao . daoMethod ( ) It) ;

i 6. I 7. I

1 Service.iava 1. package com.neo.sprlng.bean; 2. 3. public class Service {

, 4. private Dao dao: 5 .

i 6. public vold setDao (Dao dao) (

7 . this. dao = dao; i i: 1

i :i! publlc vold serviceMethod ( ) {

System. out .println ("Service. senriceMethod ( ) It) ;

dao . daoMethod ( ) ;

/ 13. I 1 1 4 . 1

Client.iava 1. package corn.neo.sprlng.cllent; 2. 3. lmport org.spr~ngframework.context.App1icationContext; 4. import org.spr~ngframework.contaxt.support.ClassPathXmlApplicationContext; 5. 6. import com.neo.sprlng.bean.Control1er; 7. 8. public class Cllent {

9. private static String[] configs = {

lo. "com/neo/spring/config/spring-controller-config.xml1~, 11. "com/neo/spring/config/spring-service-config.~l1~, 12. "com/neo/spring/config/spring-dao-config.mlll 1 ; 13. private static Applicationcontext context = new 14. ClassPathXmlApplicationContext(configs); 15. 16. public static void main (String[] args) {

17. Controller controller = (Controller) 18. context. getBean (llcontrollerref ");

19. controller. co~~trollerMethod ( ) ;

20. 1 21. 1

I 2 . <beans xmlns= "h t tp : //raw. springframework. org/schema/beans I 3 . xmlns : xsi= "ht tp: //m. ~3.0r9/200l/~~chema-instance~~

/ 4 . xmlns : p= "ht tp : //m. springframework. org/schema/p" 9

Naresh i Technologies, Opp. Satyam Theatre, Ameerpet, Hyderabad, Ph: 040-23746666,23734842 An I S 0 9001 : 2000 Certified Company . . . . - . - - - -. - - .- -. . . . . .

http://javabynataraj.blogspot.com

Page 117: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 118: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 119: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 120: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 121: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 122: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 123: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 124: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 125: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 126: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 127: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 128: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 129: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 130: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 131: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 132: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 133: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 134: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 135: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 136: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 137: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 138: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 139: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 140: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 141: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 142: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 143: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 144: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 145: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 146: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 147: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 148: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 149: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 150: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 151: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 152: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 153: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 154: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 155: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 156: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 157: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 158: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 159: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 160: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 161: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 162: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 163: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 164: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 165: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 166: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 167: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 168: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 169: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 170: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 171: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 172: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 173: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 174: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 175: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 176: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 177: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 178: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 179: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 180: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 181: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 182: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 183: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 184: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 185: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 186: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 187: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 188: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 189: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 190: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 191: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 192: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 193: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 194: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 195: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 196: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 197: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 198: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 199: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 200: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 201: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 202: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 203: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 204: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 205: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 206: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 207: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 208: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 209: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 210: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 211: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 212: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 213: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 214: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 215: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 216: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 217: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 218: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 219: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 220: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 221: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 222: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 223: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 224: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 225: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 226: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 227: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 228: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 229: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 230: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 231: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 232: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 233: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 234: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 235: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 236: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 237: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 238: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 239: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 240: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 241: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 242: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 243: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 244: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 245: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 246: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 247: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 248: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 249: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 250: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 251: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 252: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 253: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 254: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 255: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 256: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 257: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 258: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 259: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com

Page 260: Spring IOC DAO Modules by Sekhar Sir JavabynataraJ

http://javabynataraj.blogspot.com