SlideShare a Scribd company logo
1 of 19
The Spring Framework:
  A brief introduction to
   Inversion of Control




       James Brundege




                        www.synaptocode.com
What is Spring?

2 Things:

    ◦ An Inversion of Control (IoC) Container

   ◦ Utilities that provide a consistent (and simple!)
    API to many other technologies (JDBC, ORM,
AOP, Declarative Transactions, etc)
Guiding Principles of Spring
◦ Minimize dependencies on Spring

◦ Minimize dependencies between all layers of an
application.

◦ All application code should be testable, without an
application server or other complex environment

◦ Fully factor the APIs (the 90% case should be
accomplished in one line of code!)
What is Inversion of Control (IoC)?
(besides yet another confusing term for a simple concept)

IoC is all about Object dependencies.

Traditional "Pull" approach:
 ◦ Direct instantiation
 ◦ Asking a Factory for an implementation
 ◦ Looking up a service via JNDI
"Push" approach:
  ◦ Something outside of the Object "pushes" its dependencies
     into it. The Object has no knowledge of how it gets its
                 dependencies, it just assumes they are there.


The "Push" approach is called "Dependency Injection".
Pull Example
public class BookDemoServicePullImpl implements BookDemoService {


    public void addPublisherToBook(Book book) {

        BookDemoFactory factory = BookDemoFactory.getFactory();
        BookDemoDao dao = factory.getBookDemoDao();

        String isbn = book.getIsbn();
        if (book.getPublisher() == null && isbn != null) {
            Publisher publisher = dao.findPublisherByIsbn(isbn);
            book.setPublisher(publisher);
        }

    }

}
Push Example
(Dependency Injection)

public class BookDemoServiceImpl implements BookDemoService {

    private BookDemoDao dao;

    public void addPublisherToBook(Book book) {

        String isbn = book.getIsbn();
        if (book.getPublisher() == null && isbn != null) {
            Publisher publisher = dao.findPublisherByIsbn(isbn);
            book.setPublisher(publisher);
        }

    }

    public void setBookDemoDao(BookDemoDao dao) {
        this.dao = dao;
    }

}
BookDemoService Unit Test
Definitions

Dependency Injection is the act of injecting dependencies into an
 Object.

Inversion of Control is the general style of using Dependency
  Injection to wire together application layers.

Hence Spring is an Inversion of Control container. That is, it is a
 container that handles Dependency Injection for you.
Why is Dependency Injection better?
2 reasons:
  ◦ Loose Coupling
  ◦ Testability
Loose Coupling is improved because you don't hard-code
 dependencies between layers and modules. Instead you
 configure them outside. of the code This makes it easy to swap
 in a new implementation of a service, or break off a module and
 reuse it elsewhere.

Testability is improved because your Objects don't know or care
 what environment they're in as long as someone injects their
 dependencies. Hence you can deploy Objects into a test
 environment and inject Mock Objects for their dependencies
 with ease.
How Spring does Inversion of Control

◦ Write a configuration file in which you name
concrete "beans" for the interfaces between your
layers.

◦ "Wire" the application together by stating which
beans are dependent on each other.

◦ Instantiate a Spring object called an
ApplicationContext. This is a type of bean factory
that will instantiate all your other beans and handle
dependency injection.
Example Spring
applicationContext.xml
<beans>

    <bean id="bookDemoDao"

     class="com.bookdemo.dao.hibernate.BookDemoDaoHibernateImpl">

          <property name="sessionFactory">
              <ref local="sessionFactory"/>
          </property>

    </bean>

    <bean id="bookDemoService"
                  class="com.bookdemo.service.impl.BookDemoServiceImpl">

          <property name="bookDemoDao">
              <ref bean="bookDemoDao"/>
          </property>

    </bean>

</bean>
Bootstapping the IoC container

To start an app using IoC:
    ◦ Create an ApplicationContext object and tell it
           where applicationContext.xml is.
ApplicationContext appContext =
  new ClassPathXmlApplicationContext("classpath*:applicationContext.xml");




This just has to be done once on startup, and can be done
in the main() method or whatever code bootstraps the
application.
Bootstapping the IoC container
The appContext holds a single copy of each bean
declared in applicationContext.xml, so you could ask the
Context for any bean by name:
MyService service = (MyService)appContext.getBean("myService");


But don't! That is a "Pull" technique that treats the
ApplicationContext like a Factory.

Instead, make sure that applicationContext.xml connects
every bean to every other bean that needs it. None of the
beans thus have a dependency on spring.jar
Bootstapping the IoC container
For web applications the situation is simpler:

Web applications are bootstrapped by the web
container based on the web.xml file. Hence creating
an ApplicationContext on startup is as simple as a
single declaration in web.xml:
<listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
</listener>
A Spring app with no dependencies
on Spring?

When bootstrapping spring from web.xml, there are
only two pieces:
    ◦ The applicationContext.xml file
    ◦ A single tag within web.xml

Not a single line of Java code!

Therefore, not one of your custom classes has a
dependency on spring.jar
The BookDemo App
What else has Spring got?

Spring provides either implementations or fully-factored API
wrappers over these technologies:

    ◦ JDBC and DAOs
    ◦ ORM: Hibernate, iBatis, TopLink and others
    ◦ Declarative Transaction Support (without a full J2EE
        app server)
    ◦ Aspect-Oriented Programming
    ◦ Remote calls and Web Services (Axis)
    ◦ EJBs
Resources
Spring Website:
http://www.springframework.org/

Download Spring with sample applications:
http://prdownloads.sourceforge.net/springframework/spring-framework-1.2.8-with-
   dependencies.zip?download


Rod Johnson's book on Spring:
http://www.powells.com/biblio?PID=719&cgi=product&isbn=0764574833

Wikipedia:
http://en.wikipedia.org/wiki/Spring_Framework_%28Java%29

EasyMock:
http://www.easymock.org/

Echo2 (Rich Web Inteface framework)
http://www.nextapp.com/platform/echo2/echo/

More Related Content

What's hot

Creating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with ReactCreating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with Reactpeychevi
 
React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409Minko3D
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React EcosystemFITC
 
Esri Dev Summit 2009 Rest and Mvc Final
Esri Dev Summit 2009 Rest and Mvc FinalEsri Dev Summit 2009 Rest and Mvc Final
Esri Dev Summit 2009 Rest and Mvc Finalguestcd4688
 
Automated Testing on iOS
Automated Testing on iOSAutomated Testing on iOS
Automated Testing on iOSMake School
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to ReactRob Quick
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practicesYoni Goldberg
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core ConceptsDivyang Bhambhani
 
[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBox
[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBox[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBox
[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBoxKobkrit Viriyayudhakorn
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
React Native: React Meetup 3
React Native: React Meetup 3React Native: React Meetup 3
React Native: React Meetup 3Rob Gietema
 
Pieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React NativePieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React Nativetlv-ios-dev
 
Ryan Christiani I Heard React Was Good
Ryan Christiani I Heard React Was GoodRyan Christiani I Heard React Was Good
Ryan Christiani I Heard React Was GoodFITC
 
Extending Kubernetes with Operators
Extending Kubernetes with OperatorsExtending Kubernetes with Operators
Extending Kubernetes with Operatorspeychevi
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 

What's hot (20)

Lecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 SlideLecture 2: ES6 / ES2015 Slide
Lecture 2: ES6 / ES2015 Slide
 
Creating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with ReactCreating a WYSIWYG Editor with React
Creating a WYSIWYG Editor with React
 
React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409React in Native Apps - Meetup React - 20150409
React in Native Apps - Meetup React - 20150409
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React Ecosystem
 
Web workers
Web workersWeb workers
Web workers
 
Keyword driven testing in qtp
Keyword driven testing in qtpKeyword driven testing in qtp
Keyword driven testing in qtp
 
Esri Dev Summit 2009 Rest and Mvc Final
Esri Dev Summit 2009 Rest and Mvc FinalEsri Dev Summit 2009 Rest and Mvc Final
Esri Dev Summit 2009 Rest and Mvc Final
 
Automated Testing on iOS
Automated Testing on iOSAutomated Testing on iOS
Automated Testing on iOS
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practices
 
Dan Webb Presentation
Dan Webb PresentationDan Webb Presentation
Dan Webb Presentation
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBox
[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBox[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBox
[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBox
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
React Native: React Meetup 3
React Native: React Meetup 3React Native: React Meetup 3
React Native: React Meetup 3
 
Pieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React NativePieter De Baets - An introduction to React Native
Pieter De Baets - An introduction to React Native
 
Ryan Christiani I Heard React Was Good
Ryan Christiani I Heard React Was GoodRyan Christiani I Heard React Was Good
Ryan Christiani I Heard React Was Good
 
Extending Kubernetes with Operators
Extending Kubernetes with OperatorsExtending Kubernetes with Operators
Extending Kubernetes with Operators
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
Intro to React
Intro to ReactIntro to React
Intro to React
 

Viewers also liked

Dependency Injection & IoC
Dependency Injection & IoCDependency Injection & IoC
Dependency Injection & IoCDennis Loktionov
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionAndriy Buday
 
Practical Inversion Of Control
Practical Inversion Of ControlPractical Inversion Of Control
Practical Inversion Of Controlmhinze
 
20080531 Intro To Dependency Injection & Inversion Of Control
20080531 Intro To Dependency Injection & Inversion Of Control20080531 Intro To Dependency Injection & Inversion Of Control
20080531 Intro To Dependency Injection & Inversion Of Controldonnfelker
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented ProgrammingAnumod Kumar
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentationsourabh aggarwal
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 updateJoshua Long
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring FrameworkEdureka!
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkDineesha Suraweera
 

Viewers also liked (17)

Dependency Injection & IoC
Dependency Injection & IoCDependency Injection & IoC
Dependency Injection & IoC
 
Inversion of Control and Dependency Injection
Inversion of Control and Dependency InjectionInversion of Control and Dependency Injection
Inversion of Control and Dependency Injection
 
Practical Inversion Of Control
Practical Inversion Of ControlPractical Inversion Of Control
Practical Inversion Of Control
 
Agile and Frameworks
Agile and FrameworksAgile and Frameworks
Agile and Frameworks
 
20080531 Intro To Dependency Injection & Inversion Of Control
20080531 Intro To Dependency Injection & Inversion Of Control20080531 Intro To Dependency Injection & Inversion Of Control
20080531 Intro To Dependency Injection & Inversion Of Control
 
MVC
MVCMVC
MVC
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Spring framework core
Spring framework coreSpring framework core
Spring framework core
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 
Getting Started with Spring Framework
Getting Started with Spring FrameworkGetting Started with Spring Framework
Getting Started with Spring Framework
 
Spring 4 - A&BP CC
Spring 4 - A&BP CCSpring 4 - A&BP CC
Spring 4 - A&BP CC
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
Next stop: Spring 4
Next stop: Spring 4Next stop: Spring 4
Next stop: Spring 4
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Presentation Spring
Presentation SpringPresentation Spring
Presentation Spring
 

Similar to Spring Framework: An Introduction to Inversion of Control (IoC

Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAOAnushaNaidu
 
iOS app dev Training - Session1
iOS app dev Training - Session1iOS app dev Training - Session1
iOS app dev Training - Session1Hussain Behestee
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
Poco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignPoco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignJames Phillips
 
Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practiceseleksdev
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdfDeoDuaNaoHet
 
Spring (1)
Spring (1)Spring (1)
Spring (1)Aneega
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOCCarl Lu
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Hitesh-Java
 
Spring framework
Spring frameworkSpring framework
Spring frameworkAjit Koti
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)hchen1
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsSrikanth Shenoy
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDiego Lewin
 
Introduction to Spring sec1.pptx
Introduction to Spring sec1.pptxIntroduction to Spring sec1.pptx
Introduction to Spring sec1.pptxNourhanTarek23
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day trainingTroy Miles
 

Similar to Spring Framework: An Introduction to Inversion of Control (IoC (20)

Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
Spring session
Spring sessionSpring session
Spring session
 
iOS app dev Training - Session1
iOS app dev Training - Session1iOS app dev Training - Session1
iOS app dev Training - Session1
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Swiz DAO
Swiz DAOSwiz DAO
Swiz DAO
 
Spring training
Spring trainingSpring training
Spring training
 
Poco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class DesignPoco Es Mucho: WCF, EF, and Class Design
Poco Es Mucho: WCF, EF, and Class Design
 
Spring 2
Spring 2Spring 2
Spring 2
 
Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
 
2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf2-0. Spring ecosytem.pdf
2-0. Spring ecosytem.pdf
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
 
Signal Framework
Signal FrameworkSignal Framework
Signal Framework
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Introduction to Spring sec1.pptx
Introduction to Spring sec1.pptxIntroduction to Spring sec1.pptx
Introduction to Spring sec1.pptx
 
Ionic framework one day training
Ionic framework one day trainingIonic framework one day training
Ionic framework one day training
 

More from VisualBee.com

Homenagem para luiz e marcos (shared using VisualBee)
Homenagem para luiz e marcos 
 (shared using VisualBee)Homenagem para luiz e marcos 
 (shared using VisualBee)
Homenagem para luiz e marcos (shared using VisualBee)VisualBee.com
 
PowerPoint Presentation (shared using VisualBee)
PowerPoint Presentation (shared using VisualBee)PowerPoint Presentation (shared using VisualBee)
PowerPoint Presentation (shared using VisualBee)VisualBee.com
 
PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...
PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...
PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...VisualBee.com
 
The bible and I (shared using VisualBee)
The bible and I (shared using VisualBee)The bible and I (shared using VisualBee)
The bible and I (shared using VisualBee)VisualBee.com
 
bb (shared using VisualBee)
bb  
(shared using VisualBee)bb  
(shared using VisualBee)
bb (shared using VisualBee)VisualBee.com
 
Chua nhat III mua Thuong Nien - Nam C
Chua nhat III mua Thuong Nien - Nam CChua nhat III mua Thuong Nien - Nam C
Chua nhat III mua Thuong Nien - Nam CVisualBee.com
 
LA FE QUE AGRADA A DIOS
LA FE QUE AGRADA A DIOSLA FE QUE AGRADA A DIOS
LA FE QUE AGRADA A DIOSVisualBee.com
 
Martin Luther king JR
Martin Luther king JRMartin Luther king JR
Martin Luther king JRVisualBee.com
 
Diapositive 1 (shared using http://VisualBee.com).
Diapositive 1 (shared using http://VisualBee.com).Diapositive 1 (shared using http://VisualBee.com).
Diapositive 1 (shared using http://VisualBee.com).VisualBee.com
 

More from VisualBee.com (20)

Homenagem para luiz e marcos (shared using VisualBee)
Homenagem para luiz e marcos 
 (shared using VisualBee)Homenagem para luiz e marcos 
 (shared using VisualBee)
Homenagem para luiz e marcos (shared using VisualBee)
 
PowerPoint Presentation (shared using VisualBee)
PowerPoint Presentation (shared using VisualBee)PowerPoint Presentation (shared using VisualBee)
PowerPoint Presentation (shared using VisualBee)
 
PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...
PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...
PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...
 
The bible and I (shared using VisualBee)
The bible and I (shared using VisualBee)The bible and I (shared using VisualBee)
The bible and I (shared using VisualBee)
 
bb bb b
bb bb bbb bb b
bb bb b
 
bb (shared using VisualBee)
bb  
(shared using VisualBee)bb  
(shared using VisualBee)
bb (shared using VisualBee)
 
bb
bbbb
bb
 
loki
lokiloki
loki
 
ASH WEDNESDAY
ASH WEDNESDAYASH WEDNESDAY
ASH WEDNESDAY
 
hijospreferidos
hijospreferidoshijospreferidos
hijospreferidos
 
yo
yoyo
yo
 
hijo preferido
hijo preferidohijo preferido
hijo preferido
 
Alcoholismo
AlcoholismoAlcoholismo
Alcoholismo
 
west love
west lovewest love
west love
 
jaa
jaajaa
jaa
 
Chua nhat III mua Thuong Nien - Nam C
Chua nhat III mua Thuong Nien - Nam CChua nhat III mua Thuong Nien - Nam C
Chua nhat III mua Thuong Nien - Nam C
 
LA FE QUE AGRADA A DIOS
LA FE QUE AGRADA A DIOSLA FE QUE AGRADA A DIOS
LA FE QUE AGRADA A DIOS
 
Martin Luther king JR
Martin Luther king JRMartin Luther king JR
Martin Luther king JR
 
Diapositive 1 (shared using http://VisualBee.com).
Diapositive 1 (shared using http://VisualBee.com).Diapositive 1 (shared using http://VisualBee.com).
Diapositive 1 (shared using http://VisualBee.com).
 
my cara de empanaaa
my cara de empanaaamy cara de empanaaa
my cara de empanaaa
 

Spring Framework: An Introduction to Inversion of Control (IoC

  • 1. The Spring Framework: A brief introduction to Inversion of Control James Brundege www.synaptocode.com
  • 2. What is Spring? 2 Things: ◦ An Inversion of Control (IoC) Container ◦ Utilities that provide a consistent (and simple!) API to many other technologies (JDBC, ORM, AOP, Declarative Transactions, etc)
  • 3. Guiding Principles of Spring ◦ Minimize dependencies on Spring ◦ Minimize dependencies between all layers of an application. ◦ All application code should be testable, without an application server or other complex environment ◦ Fully factor the APIs (the 90% case should be accomplished in one line of code!)
  • 4. What is Inversion of Control (IoC)? (besides yet another confusing term for a simple concept) IoC is all about Object dependencies. Traditional "Pull" approach: ◦ Direct instantiation ◦ Asking a Factory for an implementation ◦ Looking up a service via JNDI "Push" approach: ◦ Something outside of the Object "pushes" its dependencies into it. The Object has no knowledge of how it gets its dependencies, it just assumes they are there. The "Push" approach is called "Dependency Injection".
  • 5.
  • 6. Pull Example public class BookDemoServicePullImpl implements BookDemoService { public void addPublisherToBook(Book book) { BookDemoFactory factory = BookDemoFactory.getFactory(); BookDemoDao dao = factory.getBookDemoDao(); String isbn = book.getIsbn(); if (book.getPublisher() == null && isbn != null) { Publisher publisher = dao.findPublisherByIsbn(isbn); book.setPublisher(publisher); } } }
  • 7. Push Example (Dependency Injection) public class BookDemoServiceImpl implements BookDemoService { private BookDemoDao dao; public void addPublisherToBook(Book book) { String isbn = book.getIsbn(); if (book.getPublisher() == null && isbn != null) { Publisher publisher = dao.findPublisherByIsbn(isbn); book.setPublisher(publisher); } } public void setBookDemoDao(BookDemoDao dao) { this.dao = dao; } }
  • 9. Definitions Dependency Injection is the act of injecting dependencies into an Object. Inversion of Control is the general style of using Dependency Injection to wire together application layers. Hence Spring is an Inversion of Control container. That is, it is a container that handles Dependency Injection for you.
  • 10. Why is Dependency Injection better? 2 reasons: ◦ Loose Coupling ◦ Testability Loose Coupling is improved because you don't hard-code dependencies between layers and modules. Instead you configure them outside. of the code This makes it easy to swap in a new implementation of a service, or break off a module and reuse it elsewhere. Testability is improved because your Objects don't know or care what environment they're in as long as someone injects their dependencies. Hence you can deploy Objects into a test environment and inject Mock Objects for their dependencies with ease.
  • 11. How Spring does Inversion of Control ◦ Write a configuration file in which you name concrete "beans" for the interfaces between your layers. ◦ "Wire" the application together by stating which beans are dependent on each other. ◦ Instantiate a Spring object called an ApplicationContext. This is a type of bean factory that will instantiate all your other beans and handle dependency injection.
  • 12. Example Spring applicationContext.xml <beans> <bean id="bookDemoDao" class="com.bookdemo.dao.hibernate.BookDemoDaoHibernateImpl"> <property name="sessionFactory"> <ref local="sessionFactory"/> </property> </bean> <bean id="bookDemoService" class="com.bookdemo.service.impl.BookDemoServiceImpl"> <property name="bookDemoDao"> <ref bean="bookDemoDao"/> </property> </bean> </bean>
  • 13. Bootstapping the IoC container To start an app using IoC: ◦ Create an ApplicationContext object and tell it where applicationContext.xml is. ApplicationContext appContext = new ClassPathXmlApplicationContext("classpath*:applicationContext.xml"); This just has to be done once on startup, and can be done in the main() method or whatever code bootstraps the application.
  • 14. Bootstapping the IoC container The appContext holds a single copy of each bean declared in applicationContext.xml, so you could ask the Context for any bean by name: MyService service = (MyService)appContext.getBean("myService"); But don't! That is a "Pull" technique that treats the ApplicationContext like a Factory. Instead, make sure that applicationContext.xml connects every bean to every other bean that needs it. None of the beans thus have a dependency on spring.jar
  • 15. Bootstapping the IoC container For web applications the situation is simpler: Web applications are bootstrapped by the web container based on the web.xml file. Hence creating an ApplicationContext on startup is as simple as a single declaration in web.xml: <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
  • 16. A Spring app with no dependencies on Spring? When bootstrapping spring from web.xml, there are only two pieces: ◦ The applicationContext.xml file ◦ A single tag within web.xml Not a single line of Java code! Therefore, not one of your custom classes has a dependency on spring.jar
  • 18. What else has Spring got? Spring provides either implementations or fully-factored API wrappers over these technologies: ◦ JDBC and DAOs ◦ ORM: Hibernate, iBatis, TopLink and others ◦ Declarative Transaction Support (without a full J2EE app server) ◦ Aspect-Oriented Programming ◦ Remote calls and Web Services (Axis) ◦ EJBs
  • 19. Resources Spring Website: http://www.springframework.org/ Download Spring with sample applications: http://prdownloads.sourceforge.net/springframework/spring-framework-1.2.8-with- dependencies.zip?download Rod Johnson's book on Spring: http://www.powells.com/biblio?PID=719&cgi=product&isbn=0764574833 Wikipedia: http://en.wikipedia.org/wiki/Spring_Framework_%28Java%29 EasyMock: http://www.easymock.org/ Echo2 (Rich Web Inteface framework) http://www.nextapp.com/platform/echo2/echo/