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




        Snehal Masne




                        www.iSnehal.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 BookDemo Application:
(A simple CRUD app)

                            User Interface




                Domai
                  n
                            Service Layer
                Model




                        Data Access Layer



                                 DB
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

Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
s_pradeep
 
webworkers
webworkerswebworkers
webworkers
Asanka Indrajith
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
Oleg Shanyuk
 
KnockoutJS and MVVM
KnockoutJS and MVVMKnockoutJS and MVVM
KnockoutJS and MVVM
Manvendra Singh
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with Flask
Make School
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
Fajar Baskoro
 
Cutting the Fat
Cutting the FatCutting the Fat
Cutting the Fat
Codemotion
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
Juio Barros
 
"this" in JavaScript
"this" in JavaScript"this" in JavaScript
"this" in JavaScript
Martha Schumann
 
Ajax
AjaxAjax
Java
JavaJava
Java
manavp
 
The Road to Native Web Components
The Road to Native Web ComponentsThe Road to Native Web Components
The Road to Native Web Components
Mike North
 
Time to React!
Time to React!Time to React!
Time to React!
STX Next
 
Web Api vs MVC
Web Api vs MVCWeb Api vs MVC
[Osxdev]7.handoff
[Osxdev]7.handoff[Osxdev]7.handoff
[Osxdev]7.handoff
NAVER D2
 
Architecting single-page front-end apps
Architecting single-page front-end appsArchitecting single-page front-end apps
Architecting single-page front-end apps
Zohar Arad
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
Stefano Paluello
 
Mobile optimization
Mobile optimizationMobile optimization
Mobile optimization
purplecabbage
 
You got your browser in my virtual machine
You got your browser in my virtual machineYou got your browser in my virtual machine
You got your browser in my virtual machine
Ean Schuessler
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 

What's hot (20)

Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
 
webworkers
webworkerswebworkers
webworkers
 
mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.mobile in the cloud with diamonds. improved.
mobile in the cloud with diamonds. improved.
 
KnockoutJS and MVVM
KnockoutJS and MVVMKnockoutJS and MVVM
KnockoutJS and MVVM
 
Building a Backend with Flask
Building a Backend with FlaskBuilding a Backend with Flask
Building a Backend with Flask
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
 
Cutting the Fat
Cutting the FatCutting the Fat
Cutting the Fat
 
Web Services with Objective-C
Web Services with Objective-CWeb Services with Objective-C
Web Services with Objective-C
 
"this" in JavaScript
"this" in JavaScript"this" in JavaScript
"this" in JavaScript
 
Ajax
AjaxAjax
Ajax
 
Java
JavaJava
Java
 
The Road to Native Web Components
The Road to Native Web ComponentsThe Road to Native Web Components
The Road to Native Web Components
 
Time to React!
Time to React!Time to React!
Time to React!
 
Web Api vs MVC
Web Api vs MVCWeb Api vs MVC
Web Api vs MVC
 
[Osxdev]7.handoff
[Osxdev]7.handoff[Osxdev]7.handoff
[Osxdev]7.handoff
 
Architecting single-page front-end apps
Architecting single-page front-end appsArchitecting single-page front-end apps
Architecting single-page front-end apps
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
 
Mobile optimization
Mobile optimizationMobile optimization
Mobile optimization
 
You got your browser in my virtual machine
You got your browser in my virtual machineYou got your browser in my virtual machine
You got your browser in my virtual machine
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 

Viewers also liked

Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
Funnelll
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02
Guo Albert
 
Arbol 5
Arbol 5Arbol 5
Arbol 5
vsyntact
 
Nutraceutical-ExecutiveSummary
Nutraceutical-ExecutiveSummaryNutraceutical-ExecutiveSummary
Nutraceutical-ExecutiveSummary
Tom McNulty
 
Ferramentas13
Ferramentas13Ferramentas13
Data Structures and Algorithms
Data Structures and AlgorithmsData Structures and Algorithms
Data Structures and Algorithms
SNEHAL MASNE
 
Conjugación
ConjugaciónConjugación
Conjugación
Enelis Diaz Leon
 
Coca Cola Mentos
Coca Cola MentosCoca Cola Mentos
Coca Cola Mentos
pillaliebres
 
To be influenced
To be influencedTo be influenced
To be influenced
Quinn Thurman
 
Nunca Retes A 1 Mujer
Nunca Retes A 1 MujerNunca Retes A 1 Mujer
Nunca Retes A 1 Mujer
pillaliebres
 
Benjamin Franklin
Benjamin FranklinBenjamin Franklin
Benjamin Franklin
wmsbierer
 
WhistleB study-on-corporate-whistleblowing-2016
WhistleB study-on-corporate-whistleblowing-2016WhistleB study-on-corporate-whistleblowing-2016
WhistleB study-on-corporate-whistleblowing-2016
Karin Henriksson
 
2007 1st Place
2007 1st Place2007 1st Place
NetObjects Fusion 2015 Manual Book
NetObjects Fusion 2015 Manual BookNetObjects Fusion 2015 Manual Book
NetObjects Fusion 2015 Manual Book
Brandon Taylor
 
Spring framework
Spring frameworkSpring framework
Spring framework
Rajkumar Singh
 
Whistleblowing Presentation
Whistleblowing PresentationWhistleblowing Presentation
Whistleblowing Presentation
katlyntrzaska
 
Analisis Karya 2 Dimensi
Analisis Karya 2 DimensiAnalisis Karya 2 Dimensi
Analisis Karya 2 Dimensi
Yoollan MW
 
Listaxe Galegos Mortos Campos Nazis
Listaxe Galegos Mortos Campos NazisListaxe Galegos Mortos Campos Nazis
Listaxe Galegos Mortos Campos Nazis
GZ-Israel
 
English 9 - The Whistle
English 9 - The WhistleEnglish 9 - The Whistle
English 9 - The Whistle
Juan Miguel Palero
 

Viewers also liked (20)

Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Spring bean mod02
Spring bean mod02Spring bean mod02
Spring bean mod02
 
Arbol 5
Arbol 5Arbol 5
Arbol 5
 
Nutraceutical-ExecutiveSummary
Nutraceutical-ExecutiveSummaryNutraceutical-ExecutiveSummary
Nutraceutical-ExecutiveSummary
 
Ferramentas13
Ferramentas13Ferramentas13
Ferramentas13
 
Data Structures and Algorithms
Data Structures and AlgorithmsData Structures and Algorithms
Data Structures and Algorithms
 
Conjugación
ConjugaciónConjugación
Conjugación
 
Coca Cola Mentos
Coca Cola MentosCoca Cola Mentos
Coca Cola Mentos
 
To be influenced
To be influencedTo be influenced
To be influenced
 
Frecuencias
FrecuenciasFrecuencias
Frecuencias
 
Nunca Retes A 1 Mujer
Nunca Retes A 1 MujerNunca Retes A 1 Mujer
Nunca Retes A 1 Mujer
 
Benjamin Franklin
Benjamin FranklinBenjamin Franklin
Benjamin Franklin
 
WhistleB study-on-corporate-whistleblowing-2016
WhistleB study-on-corporate-whistleblowing-2016WhistleB study-on-corporate-whistleblowing-2016
WhistleB study-on-corporate-whistleblowing-2016
 
2007 1st Place
2007 1st Place2007 1st Place
2007 1st Place
 
NetObjects Fusion 2015 Manual Book
NetObjects Fusion 2015 Manual BookNetObjects Fusion 2015 Manual Book
NetObjects Fusion 2015 Manual Book
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Whistleblowing Presentation
Whistleblowing PresentationWhistleblowing Presentation
Whistleblowing Presentation
 
Analisis Karya 2 Dimensi
Analisis Karya 2 DimensiAnalisis Karya 2 Dimensi
Analisis Karya 2 Dimensi
 
Listaxe Galegos Mortos Campos Nazis
Listaxe Galegos Mortos Campos NazisListaxe Galegos Mortos Campos Nazis
Listaxe Galegos Mortos Campos Nazis
 
English 9 - The Whistle
English 9 - The WhistleEnglish 9 - The Whistle
English 9 - The Whistle
 

Similar to Spring IOC

Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
AnushaNaidu
 
Spring 2
Spring 2Spring 2
Spring 2
Aruvi Thottlan
 
Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
eleksdev
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
Aneega
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
Skillwise Group
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
hchen1
 
Spring session
Spring sessionSpring session
Spring session
Gamal Shaban
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
sang nguyen
 
Dependency Injection Lightning Talk
Dependency Injection Lightning TalkDependency Injection Lightning Talk
Dependency Injection Lightning Talk
Jon Bachelor
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
Carl Lu
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDB
Michal Bigos
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
Srikanth Shenoy
 
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
James Phillips
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
Guo Albert
 
Spring framework
Spring frameworkSpring framework
Spring framework
Ajit Koti
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
James Phillips
 
Swiz DAO
Swiz DAOSwiz DAO
Swiz DAO
devaraj ns
 
Spring training
Spring trainingSpring training
Spring training
TechFerry
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
nomykk
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
meghantaylor
 

Similar to Spring IOC (20)

Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
Spring 2
Spring 2Spring 2
Spring 2
 
Lecture android best practices
Lecture   android best practicesLecture   android best practices
Lecture android best practices
 
Spring (1)
Spring (1)Spring (1)
Spring (1)
 
Skillwise-Spring framework 1
Skillwise-Spring framework 1Skillwise-Spring framework 1
Skillwise-Spring framework 1
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
 
Spring session
Spring sessionSpring session
Spring session
 
Spring from a to Z
Spring from  a to ZSpring from  a to Z
Spring from a to Z
 
Dependency Injection Lightning Talk
Dependency Injection Lightning TalkDependency Injection Lightning Talk
Dependency Injection Lightning Talk
 
The Basic Concept Of IOC
The Basic Concept Of IOCThe Basic Concept Of IOC
The Basic Concept Of IOC
 
Integration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDBIntegration Testing With ScalaTest and MongoDB
Integration Testing With ScalaTest and MongoDB
 
Effective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjectsEffective JavaFX architecture with FxObjects
Effective JavaFX architecture with FxObjects
 
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
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
Spring framework
Spring frameworkSpring framework
Spring framework
 
Ef Poco And Unit Testing
Ef Poco And Unit TestingEf Poco And Unit Testing
Ef Poco And Unit Testing
 
Swiz DAO
Swiz DAOSwiz DAO
Swiz DAO
 
Spring training
Spring trainingSpring training
Spring training
 
Spring Framework
Spring FrameworkSpring Framework
Spring Framework
 
Dependency Injection and Autofac
Dependency Injection and AutofacDependency Injection and Autofac
Dependency Injection and Autofac
 

Recently uploaded

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
Mariano Tinti
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
Edge AI and Vision Alliance
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
DianaGray10
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
tolgahangng
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 

Recently uploaded (20)

GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Mariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceXMariano G Tinti - Decoding SpaceX
Mariano G Tinti - Decoding SpaceX
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
“Building and Scaling AI Applications with the Nx AI Manager,” a Presentation...
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6UiPath Test Automation using UiPath Test Suite series, part 6
UiPath Test Automation using UiPath Test Suite series, part 6
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
Serial Arm Control in Real Time Presentation
Serial Arm Control in Real Time PresentationSerial Arm Control in Real Time Presentation
Serial Arm Control in Real Time Presentation
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 

Spring IOC

  • 1. The Spring Framework: A brief introduction to Inversion of Control Snehal Masne www.iSnehal.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. The BookDemo Application: (A simple CRUD app) User Interface Domai n Service Layer Model Data Access Layer DB
  • 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/