SlideShare a Scribd company logo
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".
The Spring Framework:A brief introduction toInversion of Control
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 (20)

PDF
Lecture 2: ES6 / ES2015 Slide
Kobkrit Viriyayudhakorn
 
PDF
Creating a WYSIWYG Editor with React
peychevi
 
PPTX
React in Native Apps - Meetup React - 20150409
Minko3D
 
PDF
An Overview of the React Ecosystem
FITC
 
PDF
Web workers
Surbhi Mathur
 
DOCX
Keyword driven testing in qtp
TrainigHubin India
 
PDF
Esri Dev Summit 2009 Rest and Mvc Final
guestcd4688
 
PDF
Automated Testing on iOS
Make School
 
PPTX
Introduction to React
Rob Quick
 
PPTX
Node.JS error handling best practices
Yoni Goldberg
 
PDF
Dan Webb Presentation
RubyOnRails_dude
 
PPTX
React js - The Core Concepts
Divyang Bhambhani
 
PDF
[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBox
Kobkrit Viriyayudhakorn
 
PPTX
Introduction to React JS for beginners
Varun Raj
 
PDF
React Native: React Meetup 3
Rob Gietema
 
PDF
Pieter De Baets - An introduction to React Native
tlv-ios-dev
 
PDF
Ryan Christiani I Heard React Was Good
FITC
 
PDF
Extending Kubernetes with Operators
peychevi
 
PPTX
React JS: A Secret Preview
valuebound
 
PPTX
Intro to React
Eric Westfall
 
Lecture 2: ES6 / ES2015 Slide
Kobkrit Viriyayudhakorn
 
Creating a WYSIWYG Editor with React
peychevi
 
React in Native Apps - Meetup React - 20150409
Minko3D
 
An Overview of the React Ecosystem
FITC
 
Web workers
Surbhi Mathur
 
Keyword driven testing in qtp
TrainigHubin India
 
Esri Dev Summit 2009 Rest and Mvc Final
guestcd4688
 
Automated Testing on iOS
Make School
 
Introduction to React
Rob Quick
 
Node.JS error handling best practices
Yoni Goldberg
 
Dan Webb Presentation
RubyOnRails_dude
 
React js - The Core Concepts
Divyang Bhambhani
 
[React Native] Lecture 4: Basic Elements and UI Layout by using FlexBox
Kobkrit Viriyayudhakorn
 
Introduction to React JS for beginners
Varun Raj
 
React Native: React Meetup 3
Rob Gietema
 
Pieter De Baets - An introduction to React Native
tlv-ios-dev
 
Ryan Christiani I Heard React Was Good
FITC
 
Extending Kubernetes with Operators
peychevi
 
React JS: A Secret Preview
valuebound
 
Intro to React
Eric Westfall
 

Viewers also liked (17)

PPT
Dependency Injection & IoC
Dennis Loktionov
 
PPT
Inversion of Control and Dependency Injection
Andriy Buday
 
PPT
Practical Inversion Of Control
mhinze
 
PDF
Agile and Frameworks
Sander Hoogendoorn
 
PPT
20080531 Intro To Dependency Injection & Inversion Of Control
donnfelker
 
PPT
MVC
akshin
 
PPT
Aspect Oriented Programming
Anumod Kumar
 
ODP
Spring 4 final xtr_presentation
sourabh aggarwal
 
PDF
Spring framework core
Taemon Piya-Lumyong
 
PDF
the Spring 4 update
Joshua Long
 
PDF
Getting Started with Spring Framework
Edureka!
 
PDF
Spring 4 - A&BP CC
JWORKS powered by Ordina
 
PDF
Spring 4 Web App
Rossen Stoyanchev
 
PPTX
Next stop: Spring 4
Oleg Tsal-Tsalko
 
PPTX
Introduction to Spring Framework
Dineesha Suraweera
 
PPT
Spring ppt
Mumbai Academisc
 
PPT
Presentation Spring
Nathaniel Richand
 
Dependency Injection & IoC
Dennis Loktionov
 
Inversion of Control and Dependency Injection
Andriy Buday
 
Practical Inversion Of Control
mhinze
 
Agile and Frameworks
Sander Hoogendoorn
 
20080531 Intro To Dependency Injection & Inversion Of Control
donnfelker
 
MVC
akshin
 
Aspect Oriented Programming
Anumod Kumar
 
Spring 4 final xtr_presentation
sourabh aggarwal
 
Spring framework core
Taemon Piya-Lumyong
 
the Spring 4 update
Joshua Long
 
Getting Started with Spring Framework
Edureka!
 
Spring 4 - A&BP CC
JWORKS powered by Ordina
 
Spring 4 Web App
Rossen Stoyanchev
 
Next stop: Spring 4
Oleg Tsal-Tsalko
 
Introduction to Spring Framework
Dineesha Suraweera
 
Spring ppt
Mumbai Academisc
 
Presentation Spring
Nathaniel Richand
 
Ad

Similar to The Spring Framework: A brief introduction to Inversion of Control (20)

PPTX
Spring IOC and DAO
AnushaNaidu
 
PPTX
Spring session
Gamal Shaban
 
PPTX
iOS app dev Training - Session1
Hussain Behestee
 
PPTX
Spring framework
Rajkumar Singh
 
PDF
Swiz DAO
devaraj ns
 
PPT
Spring training
TechFerry
 
PPTX
Poco Es Mucho: WCF, EF, and Class Design
James Phillips
 
PDF
Spring 2
Aruvi Thottlan
 
PPTX
Lecture android best practices
eleksdev
 
PDF
2-0. Spring ecosytem.pdf
DeoDuaNaoHet
 
PPTX
Spring (1)
Aneega
 
PDF
The Basic Concept Of IOC
Carl Lu
 
PPSX
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
PPT
Spring framework
Ajit Koti
 
PPT
Gnizr Architecture (for developers)
hchen1
 
PDF
Signal Framework
Aurora Softworks
 
PDF
Effective JavaFX architecture with FxObjects
Srikanth Shenoy
 
ODP
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
PPTX
Introduction to Spring sec1.pptx
NourhanTarek23
 
PDF
Ionic framework one day training
Troy Miles
 
Spring IOC and DAO
AnushaNaidu
 
Spring session
Gamal Shaban
 
iOS app dev Training - Session1
Hussain Behestee
 
Spring framework
Rajkumar Singh
 
Swiz DAO
devaraj ns
 
Spring training
TechFerry
 
Poco Es Mucho: WCF, EF, and Class Design
James Phillips
 
Spring 2
Aruvi Thottlan
 
Lecture android best practices
eleksdev
 
2-0. Spring ecosytem.pdf
DeoDuaNaoHet
 
Spring (1)
Aneega
 
The Basic Concept Of IOC
Carl Lu
 
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Spring framework
Ajit Koti
 
Gnizr Architecture (for developers)
hchen1
 
Signal Framework
Aurora Softworks
 
Effective JavaFX architecture with FxObjects
Srikanth Shenoy
 
Dependency Injection, Zend Framework and Symfony Container
Diego Lewin
 
Introduction to Spring sec1.pptx
NourhanTarek23
 
Ionic framework one day training
Troy Miles
 
Ad

More from VisualBee.com (20)

PPTX
Homenagem para luiz e marcos (shared using VisualBee)
VisualBee.com
 
PPTX
PowerPoint Presentation (shared using VisualBee)
VisualBee.com
 
PPTX
PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...
VisualBee.com
 
PPTX
The bible and I (shared using VisualBee)
VisualBee.com
 
PPTX
bb bb b
VisualBee.com
 
PPTX
bb (shared using VisualBee)
VisualBee.com
 
PDF
loki
VisualBee.com
 
PPTX
ASH WEDNESDAY
VisualBee.com
 
PPTX
hijospreferidos
VisualBee.com
 
PPTX
hijo preferido
VisualBee.com
 
PPTX
Alcoholismo
VisualBee.com
 
PPTX
west love
VisualBee.com
 
PPTX
jaa
VisualBee.com
 
PPTX
Chua nhat III mua Thuong Nien - Nam C
VisualBee.com
 
PPTX
LA FE QUE AGRADA A DIOS
VisualBee.com
 
PPTX
Martin Luther king JR
VisualBee.com
 
PPTX
Diapositive 1 (shared using http://VisualBee.com).
VisualBee.com
 
PPTX
my cara de empanaaa
VisualBee.com
 
Homenagem para luiz e marcos (shared using VisualBee)
VisualBee.com
 
PowerPoint Presentation (shared using VisualBee)
VisualBee.com
 
PowerPoint Presentation (shared using http://VisualBee.com). (shared using Vi...
VisualBee.com
 
The bible and I (shared using VisualBee)
VisualBee.com
 
bb bb b
VisualBee.com
 
bb (shared using VisualBee)
VisualBee.com
 
ASH WEDNESDAY
VisualBee.com
 
hijospreferidos
VisualBee.com
 
hijo preferido
VisualBee.com
 
Alcoholismo
VisualBee.com
 
west love
VisualBee.com
 
Chua nhat III mua Thuong Nien - Nam C
VisualBee.com
 
LA FE QUE AGRADA A DIOS
VisualBee.com
 
Martin Luther king JR
VisualBee.com
 
Diapositive 1 (shared using http://VisualBee.com).
VisualBee.com
 
my cara de empanaaa
VisualBee.com
 

The Spring Framework: A brief introduction to Inversion of Control

  • 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".
  • 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/