SlideShare ist ein Scribd-Unternehmen logo
1 von 36
Dependency Injection




     rgupta.trainer@gmail.com
Dependency Injection
•  Hello World DI
•  Using setter, Constructor Injection
•  Injecting Objects
•  Inner Beans, Aliases
•  Initializing Collections
•  Understanding Bean Scopes
•  Bean Autowiring
•  Using ApplicationContextAware
•  Bean Definition Inheritance
•  Lifecycle Callbacks
•  Method injections
•  Lookup method injection
• …
• …


                              rgupta.trainer@gmail.com
Introduction to DI




    rgupta.trainer@gmail.com
interface




Design as per interface




                          rgupta.trainer@gmail.com
Car depends on Wheel




                       rgupta.trainer@gmail.com
Most important :glue it all with XML




                       rgupta.trainer@gmail.com
DI ?
• DI is how objects or bean using Spring are brought together by container
  to accomplished the task

• It is AKA of IoC

• In most application and object is responsible for its own dependencies or
  associated objects and this is mostly achieved using JNDI

• In DI approach we allow container to manages dependencies of object
  creation and association


Hollywood ; don’t call me I will call you



                                rgupta.trainer@gmail.com
How Spring Work?




    rgupta.trainer@gmail.com
• Any object outside
  container get bean by
  providing ref

• We know object requiring
  bean contact to container ie
  Application context that
  refer SpringXML and create
  a Spring managed bean and
  that can be referred by
  requesting object
  outside/inside the
  container



                          rgupta.trainer@gmail.com
Spring Hello world example




         rgupta.trainer@gmail.com
rgupta.trainer@gmail.com
Setter injection….Ex




      rgupta.trainer@gmail.com
Injecting Objects




    rgupta.trainer@gmail.com
rgupta.trainer@gmail.com
Inner Beans
• Remove the definition of
  Point bean and put into
  triangle bean

• Remove the ref tag and put
  definition inside.

• No performance adv.

• whenever a bean is used for
  only one particular property,
  it’s advise to declare it as an
  inner bean
                               rgupta.trainer@gmail.com
Aliases

• alias giving name
  to same bean
• Use alias tag
• Now bean can be
  referred by new
  name


                      rgupta.trainer@gmail.com
Spring bean scopes

• In Spring, bean scope is used to decide which
  type of bean instance should be return from
  Spring container back to the caller.

• In most cases, you may only deal with the
  Spring’s core scope – singleton and prototype,
  and the default scope is singleton.


                   rgupta.trainer@gmail.com
Bean Scopes
           Scope                                    Description
          Singleton          (Default)Only one single instance will be
                             created

          Prototype          Creates any number of instances from a
                             single bean configuration

           Request           Scope of the bean instance will be limited to
                             the Request life cycle

           Session           Limited to session

        Global session       Limited to global session- Portlet context.


<bean name =“student” class =“Student” scope =“prototype”/>
                         rgupta.trainer@gmail.com
Singleton scope
ctx.getBean(“student”)




                            Spring
                           Container                Single student
                                                    instance




                         rgupta.trainer@gmail.com
Output in case of
default bean scope


                     rgupta.trainer@gmail.com
Prototype scope
ctx.getBean(“student”)




                            Spring
                           Container
                                                    Multiple Beans




                         rgupta.trainer@gmail.com
rgupta.trainer@gmail.com
Spring Collection
• What if member variable is collection
  major collection types are supported in
  Spring

  List – <list/>
  Set – <set/>
  Map – <map/>
  Properties – <props/>


              rgupta.trainer@gmail.com
Injecting list..




rgupta.trainer@gmail.com
rgupta.trainer@gmail.com
Auto Wiring

• Skip some of the configuration that we have
  to do by intelligent guessing what ref is
• AKA shortcut.
• Type of auto wiring
  – byName
  – byType (for only one composite object)
  – constructor


                    rgupta.trainer@gmail.com
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans.xsd">


<bean id="tringle" class="com.ex3.code.Tringle" autowire="byName">

</bean>

<bean id="pointA" class="com.ex3.code.Point">
<property name="x" value="0"/>
<property name="y" value="0"/>
</bean>

<bean id="pointB" class="com.ex3.code.Point">
<property name="x" value="20"/>
<property name="y" value="0"/>
</bean>


<bean id="pointC" class="com.ex3.code.Point">
<property name="x" value="-20"/>
<property name="y" value="0"/>
</bean>


<alias name="tringle" alias="my-tringle"/>

</beans>



                                             rgupta.trainer@gmail.com
Aware interfaces..


• BeanName Aware interface
     • Want to know the name of bean configured
• ApplicationContextAware
     • Getting Application context
     • We need to implements ApplicationContextAware


     Container itself call setter related to aware interface
      before creation of any bean.

                        rgupta.trainer@gmail.com
Bean Definition Inheritance
• Lets say we have 100 bean definition in xml ,
  lets we have common definition in each bean
  definition aka template




                   rgupta.trainer@gmail.com
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="parenttringle" class="com.ex3.code.Tringle">
<property name="pointA" ref="firstPoint"></property>
</bean>


<bean id="tringle" class="com.ex3.code.Tringle" parent="parenttringle">
<property name="pointC" ref="secPoint"></property>
<property name="pointC" ref="thirdPoint"></property>
</bean>

<bean id="firstPoint" class="com.ex3.code.Point">
<property name="x" value="0"/>
<property name="y" value="0"/>
</bean>

<bean id="secPoint" class="com.ex3.code.Point">
<property name="x" value="20"/>
<property name="y" value="0"/>
</bean>


<bean id="thirdPoint" class="com.ex3.code.Point">
<property name="x" value="-20"/>
<property name="y" value="0"/>
</bean>


<alias name="tringle" alias="my-tringle"/>

</beans>




                                                     rgupta.trainer@gmail.com
Lifecycle Callbacks
• Spring provide us call-back method for life cycle
  of bean
           • for initialization of bean
           • for cleanup of bean


EX: Shut down hook
           • closing app context for SE applications
           • use class AbstractAppicationContext, when main finished

AbstractApplicationContext ctx=new ClassPathXmlApplicationContext("springWithAutoWiring.xml");
ctx.registerShutdownHook();



                                        rgupta.trainer@gmail.com
cofig init and destroyed method
• Choice I
            • implements InitializingBean,DisposableBean
• Choice II
            • Dont want to bind to spring interface interfaces......

<bean id="tringle" class="com.ex3.code.Tringle" autowire="byName" init-method="myInit" destroy-
    method="myDestroy">




What happens if both are there?
 first spring then my method is called.

                                          rgupta.trainer@gmail.com
public class Tringle implements
                                              public void setPointC(Point pointC) {
      InitializingBean,DisposableBean{        this.pointC = pointC;
                                              }
private Point pointA;                         public void draw() {
private Point pointB;                         System.out.println(pointA);
                                              System.out.println(pointB);
private Point pointC;                         System.out.println(pointC);
                                              }
public Point getPointA() {
                                              @Override
return pointA;                                public void afterPropertiesSet() throws Exception {
                                              // TODO Auto-generated method stub
}                                             System.out.println("called after init of bean");
public void setPointA(Point pointA) {         }
                                              @Override
this.pointA = pointA;                         public void destroy() throws Exception {
                                              System.out.println("called after destruction of bean");
}                                             }

public Point getPointB() {
                                              }
return pointB;                                }
}
public void setPointB(Point pointB) {
this.pointB = pointB;
}
public Point getPointC() {
return pointC;
}




                                         rgupta.trainer@gmail.com
Method Injection – Method Replace
          class MobileStore{
                   public String buyMobile(){
                  return "Bought a Mobile Phone";
          }}


class MobileStoreReplacer implements MethodReplacer{
         public Object reimplement(Object obj, Method method, Object[] args)
                   throws Throwable{
         return “Bought an iPhone”;

                  }
}

<bean id =“mobileStore” class =“MobileStore”>
    <replace-method name =“buyMobile” replacer =“mobileStoreReplacer”/>
</bean>

<bean id =“mobileStoreReplacer” class =“MobileStoreReplacer”/>
                             rgupta.trainer@gmail.com
Lookup Method Injection
public abstract class BookStore {                     public interface Book {
                                                      public String bookTitle();
public abstract Book orderBook();                     }
}
                                                                 Managed by Spring
 public class StoryBook implements Book{                 public class ProgrammingBook
 public String bookTitle() {                               implements Book{
 return "HarryPotter“; }                                 public String bookTitle() {
 }                                                       return "spring programming“; }
                                                         }



 • The ability of the container to override methods on
   container managed beans, to return the lookup
   result for another named bean in the container.

                                     rgupta.trainer@gmail.com
Thanks !!!




 rgupta.trainer@gmail.com

Weitere ähnliche Inhalte

Was ist angesagt?

Five class-based views everyone has written by now
Five class-based views everyone has written by nowFive class-based views everyone has written by now
Five class-based views everyone has written by now
James Aylett
 
Cool Object Building With PHP
Cool Object Building With PHPCool Object Building With PHP
Cool Object Building With PHP
wensheng wei
 
Developing components and extensions for ext js
Developing components and extensions for ext jsDeveloping components and extensions for ext js
Developing components and extensions for ext js
Mats Bryntse
 

Was ist angesagt? (20)

파이썬 플라스크로 배우는 웹프로그래밍 #4 (ABCD)
파이썬 플라스크로 배우는 웹프로그래밍 #4 (ABCD)파이썬 플라스크로 배우는 웹프로그래밍 #4 (ABCD)
파이썬 플라스크로 배우는 웹프로그래밍 #4 (ABCD)
 
Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)
 
Five class-based views everyone has written by now
Five class-based views everyone has written by nowFive class-based views everyone has written by now
Five class-based views everyone has written by now
 
Advanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and MonitoringAdvanced GORM - Performance, Customization and Monitoring
Advanced GORM - Performance, Customization and Monitoring
 
JavaScript Libraries Overview
JavaScript Libraries OverviewJavaScript Libraries Overview
JavaScript Libraries Overview
 
The Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contribThe Django Book, Chapter 16: django.contrib
The Django Book, Chapter 16: django.contrib
 
Powerful Generic Patterns With Django
Powerful Generic Patterns With DjangoPowerful Generic Patterns With Django
Powerful Generic Patterns With Django
 
201204 random clustering
201204 random clustering201204 random clustering
201204 random clustering
 
Cool Object Building With PHP
Cool Object Building With PHPCool Object Building With PHP
Cool Object Building With PHP
 
Spring
SpringSpring
Spring
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Patterns In-Javascript
Patterns In-JavascriptPatterns In-Javascript
Patterns In-Javascript
 
JS Level Up: Prototypes
JS Level Up: PrototypesJS Level Up: Prototypes
JS Level Up: Prototypes
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Attribute
AttributeAttribute
Attribute
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Developing components and extensions for ext js
Developing components and extensions for ext jsDeveloping components and extensions for ext js
Developing components and extensions for ext js
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Akka and the Zen of Reactive System Design
Akka and the Zen of Reactive System DesignAkka and the Zen of Reactive System Design
Akka and the Zen of Reactive System Design
 

Ähnlich wie Spring 3.0 dependancy injection

Spring framework
Spring frameworkSpring framework
Spring framework
Ajit Koti
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
srmelody
 
Objective C 基本介紹
Objective C 基本介紹Objective C 基本介紹
Objective C 基本介紹
Giga Cheng
 
Test in action week 3
Test in action   week 3Test in action   week 3
Test in action week 3
Yi-Huan Chan
 
把鐵路開進視窗裡
把鐵路開進視窗裡把鐵路開進視窗裡
把鐵路開進視窗裡
Wei Jen Lu
 

Ähnlich wie Spring 3.0 dependancy injection (20)

Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...Singletons in PHP - Why they are bad and how you can eliminate them from your...
Singletons in PHP - Why they are bad and how you can eliminate them from your...
 
Spring talk111204
Spring talk111204Spring talk111204
Spring talk111204
 
Using java beans(ii)
Using java beans(ii)Using java beans(ii)
Using java beans(ii)
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
What's New in Enterprise JavaBean Technology ?
What's New in Enterprise JavaBean Technology ?What's New in Enterprise JavaBean Technology ?
What's New in Enterprise JavaBean Technology ?
 
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
 
Story ofcorespring infodeck
Story ofcorespring infodeckStory ofcorespring infodeck
Story ofcorespring infodeck
 
Spring framework IOC and Dependency Injection
Spring framework  IOC and Dependency InjectionSpring framework  IOC and Dependency Injection
Spring framework IOC and Dependency Injection
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
java beans
java beansjava beans
java beans
 
Objective C 基本介紹
Objective C 基本介紹Objective C 基本介紹
Objective C 基本介紹
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
 
Test in action week 3
Test in action   week 3Test in action   week 3
Test in action week 3
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring essentials 2 Spring Series 02)
Spring essentials 2 Spring Series 02)Spring essentials 2 Spring Series 02)
Spring essentials 2 Spring Series 02)
 
Magento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request FlowMagento Live Australia 2016: Request Flow
Magento Live Australia 2016: Request Flow
 
What's new in Django 1.2?
What's new in Django 1.2?What's new in Django 1.2?
What's new in Django 1.2?
 
把鐵路開進視窗裡
把鐵路開進視窗裡把鐵路開進視窗裡
把鐵路開進視窗裡
 

Mehr von Rajiv Gupta

Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2
Rajiv Gupta
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4j
Rajiv Gupta
 
Core java 5 days workshop stuff
Core java 5 days workshop stuffCore java 5 days workshop stuff
Core java 5 days workshop stuff
Rajiv Gupta
 

Mehr von Rajiv Gupta (18)

Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by step
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentals
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Weblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastWeblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencast
 
Struts2
Struts2Struts2
Struts2
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
Java 7
Java 7Java 7
Java 7
 
Struts2 notes
Struts2 notesStruts2 notes
Struts2 notes
 
Lab work servlets and jsp
Lab work servlets and jspLab work servlets and jsp
Lab work servlets and jsp
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Spring aop with aspect j
Spring aop with aspect jSpring aop with aspect j
Spring aop with aspect j
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Jsp Notes
Jsp NotesJsp Notes
Jsp Notes
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4j
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
Core java 5 days workshop stuff
Core java 5 days workshop stuffCore java 5 days workshop stuff
Core java 5 days workshop stuff
 

Kürzlich hochgeladen

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Kürzlich hochgeladen (20)

Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 

Spring 3.0 dependancy injection

  • 1. Dependency Injection rgupta.trainer@gmail.com
  • 2. Dependency Injection • Hello World DI • Using setter, Constructor Injection • Injecting Objects • Inner Beans, Aliases • Initializing Collections • Understanding Bean Scopes • Bean Autowiring • Using ApplicationContextAware • Bean Definition Inheritance • Lifecycle Callbacks • Method injections • Lookup method injection • … • … rgupta.trainer@gmail.com
  • 3. Introduction to DI rgupta.trainer@gmail.com
  • 4. interface Design as per interface rgupta.trainer@gmail.com
  • 5. Car depends on Wheel rgupta.trainer@gmail.com
  • 6. Most important :glue it all with XML rgupta.trainer@gmail.com
  • 7. DI ? • DI is how objects or bean using Spring are brought together by container to accomplished the task • It is AKA of IoC • In most application and object is responsible for its own dependencies or associated objects and this is mostly achieved using JNDI • In DI approach we allow container to manages dependencies of object creation and association Hollywood ; don’t call me I will call you  rgupta.trainer@gmail.com
  • 8. How Spring Work? rgupta.trainer@gmail.com
  • 9. • Any object outside container get bean by providing ref • We know object requiring bean contact to container ie Application context that refer SpringXML and create a Spring managed bean and that can be referred by requesting object outside/inside the container rgupta.trainer@gmail.com
  • 10. Spring Hello world example rgupta.trainer@gmail.com
  • 12. Setter injection….Ex rgupta.trainer@gmail.com
  • 13. Injecting Objects rgupta.trainer@gmail.com
  • 15. Inner Beans • Remove the definition of Point bean and put into triangle bean • Remove the ref tag and put definition inside. • No performance adv. • whenever a bean is used for only one particular property, it’s advise to declare it as an inner bean rgupta.trainer@gmail.com
  • 16. Aliases • alias giving name to same bean • Use alias tag • Now bean can be referred by new name rgupta.trainer@gmail.com
  • 17. Spring bean scopes • In Spring, bean scope is used to decide which type of bean instance should be return from Spring container back to the caller. • In most cases, you may only deal with the Spring’s core scope – singleton and prototype, and the default scope is singleton. rgupta.trainer@gmail.com
  • 18. Bean Scopes Scope Description Singleton (Default)Only one single instance will be created Prototype Creates any number of instances from a single bean configuration Request Scope of the bean instance will be limited to the Request life cycle Session Limited to session Global session Limited to global session- Portlet context. <bean name =“student” class =“Student” scope =“prototype”/> rgupta.trainer@gmail.com
  • 19. Singleton scope ctx.getBean(“student”) Spring Container Single student instance rgupta.trainer@gmail.com
  • 20. Output in case of default bean scope rgupta.trainer@gmail.com
  • 21. Prototype scope ctx.getBean(“student”) Spring Container Multiple Beans rgupta.trainer@gmail.com
  • 23. Spring Collection • What if member variable is collection major collection types are supported in Spring List – <list/> Set – <set/> Map – <map/> Properties – <props/> rgupta.trainer@gmail.com
  • 26. Auto Wiring • Skip some of the configuration that we have to do by intelligent guessing what ref is • AKA shortcut. • Type of auto wiring – byName – byType (for only one composite object) – constructor rgupta.trainer@gmail.com
  • 27. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="tringle" class="com.ex3.code.Tringle" autowire="byName"> </bean> <bean id="pointA" class="com.ex3.code.Point"> <property name="x" value="0"/> <property name="y" value="0"/> </bean> <bean id="pointB" class="com.ex3.code.Point"> <property name="x" value="20"/> <property name="y" value="0"/> </bean> <bean id="pointC" class="com.ex3.code.Point"> <property name="x" value="-20"/> <property name="y" value="0"/> </bean> <alias name="tringle" alias="my-tringle"/> </beans> rgupta.trainer@gmail.com
  • 28. Aware interfaces.. • BeanName Aware interface • Want to know the name of bean configured • ApplicationContextAware • Getting Application context • We need to implements ApplicationContextAware Container itself call setter related to aware interface before creation of any bean. rgupta.trainer@gmail.com
  • 29. Bean Definition Inheritance • Lets say we have 100 bean definition in xml , lets we have common definition in each bean definition aka template rgupta.trainer@gmail.com
  • 30. <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="parenttringle" class="com.ex3.code.Tringle"> <property name="pointA" ref="firstPoint"></property> </bean> <bean id="tringle" class="com.ex3.code.Tringle" parent="parenttringle"> <property name="pointC" ref="secPoint"></property> <property name="pointC" ref="thirdPoint"></property> </bean> <bean id="firstPoint" class="com.ex3.code.Point"> <property name="x" value="0"/> <property name="y" value="0"/> </bean> <bean id="secPoint" class="com.ex3.code.Point"> <property name="x" value="20"/> <property name="y" value="0"/> </bean> <bean id="thirdPoint" class="com.ex3.code.Point"> <property name="x" value="-20"/> <property name="y" value="0"/> </bean> <alias name="tringle" alias="my-tringle"/> </beans> rgupta.trainer@gmail.com
  • 31. Lifecycle Callbacks • Spring provide us call-back method for life cycle of bean • for initialization of bean • for cleanup of bean EX: Shut down hook • closing app context for SE applications • use class AbstractAppicationContext, when main finished AbstractApplicationContext ctx=new ClassPathXmlApplicationContext("springWithAutoWiring.xml"); ctx.registerShutdownHook(); rgupta.trainer@gmail.com
  • 32. cofig init and destroyed method • Choice I • implements InitializingBean,DisposableBean • Choice II • Dont want to bind to spring interface interfaces...... <bean id="tringle" class="com.ex3.code.Tringle" autowire="byName" init-method="myInit" destroy- method="myDestroy"> What happens if both are there? first spring then my method is called. rgupta.trainer@gmail.com
  • 33. public class Tringle implements public void setPointC(Point pointC) { InitializingBean,DisposableBean{ this.pointC = pointC; } private Point pointA; public void draw() { private Point pointB; System.out.println(pointA); System.out.println(pointB); private Point pointC; System.out.println(pointC); } public Point getPointA() { @Override return pointA; public void afterPropertiesSet() throws Exception { // TODO Auto-generated method stub } System.out.println("called after init of bean"); public void setPointA(Point pointA) { } @Override this.pointA = pointA; public void destroy() throws Exception { System.out.println("called after destruction of bean"); } } public Point getPointB() { } return pointB; } } public void setPointB(Point pointB) { this.pointB = pointB; } public Point getPointC() { return pointC; } rgupta.trainer@gmail.com
  • 34. Method Injection – Method Replace class MobileStore{ public String buyMobile(){ return "Bought a Mobile Phone"; }} class MobileStoreReplacer implements MethodReplacer{ public Object reimplement(Object obj, Method method, Object[] args) throws Throwable{ return “Bought an iPhone”; } } <bean id =“mobileStore” class =“MobileStore”> <replace-method name =“buyMobile” replacer =“mobileStoreReplacer”/> </bean> <bean id =“mobileStoreReplacer” class =“MobileStoreReplacer”/> rgupta.trainer@gmail.com
  • 35. Lookup Method Injection public abstract class BookStore { public interface Book { public String bookTitle(); public abstract Book orderBook(); } } Managed by Spring public class StoryBook implements Book{ public class ProgrammingBook public String bookTitle() { implements Book{ return "HarryPotter“; } public String bookTitle() { } return "spring programming“; } } • The ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. rgupta.trainer@gmail.com