SlideShare uma empresa Scribd logo
1 de 12
Baixar para ler offline
Overview of Dependency
   Injection in Spring

       Richard Paul
      Kiwiplan NZ Ltd
       27 Mar 2009
What is Dependency Injection
Dependency Injection is a form of Inversion of Control.
Also known as the Hollywood principle,
quot;Don't call us, we'll call you!quot;

MyService is given instances of ItemDAO and
LabelDAO. MyService isn't responsible for looking up DAOs.
Benefits of Dependency Injection

Ensures configuration and usages of services are separate.

Can switch implementations by simply changing the
configuration.

Enhances testability as mock dependencies can be injected

Dependencies are easily identified
     No need to read the source code to see what
     dependencies your code talks to.
Constructor vs Setter Injection
// Constructor
public class MyService implement Service {
  private ItemDAO itemDAO;
  private LabelDAO labelDAO;

    public MyService(ItemDAO itemDAO, LabelDAO labelDAO) {
      this.itemDAO = itemDAO;
      this.labelDAO = labelDAO;
    }
}
// Setter
public class MyService implement Service {
  private ItemDAO itemDAO;
  private LabelDAO labelDAO;

    public setItemDAO(ItemDAO itemDAO) {
      this.itemDAO = itemDAO;
    }
    public setLabelDAO(LabelDAO labelDAO) {
      this.labelDAO = labelDAO;
    }
}
Constructor vs Setter Injection

Both constructor and setter injection provide:
   Loose coupling
   Separation of configuration and usage
   Enhanced testability

Constructor injection has a slight advantage (IMO) as it is
upfront about what collaborators it requires.



More details at:
http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/
Dependency Injection in Spring

There are multiple ways of setting up the dependency
configuration in spring.
   XML
   Annotations
   JavaConfig
   ...

It is possible to mix and match definition styles.
XML

Give myService access to labelDAO .
<bean id=quot;labelDAOquot; class=quot;com.example.dao.MyLabelDAOquot;/>

<!-- Constructor Injection -->
<bean id=quot;myService1quot; class=quot;com.example.service.MyServiceImplquot;>
  <constructor-arg ref=quot;labelDAOquot;/>
</bean>

<!-- Setter Injection -->
<bean id=quot;myService2quot; class=quot;com.example.service.MyServiceImplquot;>
  <property name=quot;labelDAOquot; ref=quot;labelDAOquot;/>
</bean>
XML - Multiple Files

The XML configuration can be split amoung multiple files. With
each file containing configuration for different areas.
   applicationContext.xml
   controllers.xml
   dao.xml
   ...
Annotations - Example

You can by-pass some of the XML configuration by using
Spring's annotation support.
@Service
public class MyServiceImpl implement MyService {
  private ItemDAO itemDAO;
  private LabelDAO labelDAO;

    @Autowired
    public MyService(ItemDAO itemDAO, LabelDAO labelDAO) {
      this.itemDAO = itemDAO;
      this.labelDAO = labelDAO;
    }
}

@Repository
public class MyItemDAO implements ItemDAO {
  // ...
}
Annotations - Listing

There are many available annotation for wiring:

@Autowired
@Required
@Qualifier(quot;xxxquot;)
@PostConstruct/@PreDestroy
@Resource - JSR-250
@Component
@Service
@Respository
@Controller

http://static.springframework.org/spring/docs/2.5.x/reference/beans.
html#beans-annotation-config
Java Config

Dependency Injection with configuration done using Java. Uses
annotations and replaces the XML config with Java code.

@Configuration
public class AppConfig {
  @Bean
  public Foo foo() {
    return new Foo(bar());
  }
  @Bean
  public Bar bar() {
    return new Bar();
  }
}
Alternatives

The main alternative to Spring's Dependency Injection is Guice.

More info available at:
http://www.infoq.com/news/2007/03/guice-javaconfig




                         Questions?

Mais conteúdo relacionado

Mais procurados

Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & ActuatorsVMware Tanzu
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentationAhasanul Kalam Akib
 
ASP.NET State management
ASP.NET State managementASP.NET State management
ASP.NET State managementShivanand Arur
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewShahed Chowdhuri
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjsmanojbkalla
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type scriptRemo Jansen
 

Mais procurados (20)

Spring Core
Spring CoreSpring Core
Spring Core
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Spring Boot & Actuators
Spring Boot & ActuatorsSpring Boot & Actuators
Spring Boot & Actuators
 
Spring Security
Spring SecuritySpring Security
Spring Security
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
React js
React jsReact js
React js
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentation
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
ASP.NET State management
ASP.NET State managementASP.NET State management
ASP.NET State management
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Spring boot
Spring bootSpring boot
Spring boot
 
ASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with OverviewASP.NET Core MVC + Web API with Overview
ASP.NET Core MVC + Web API with Overview
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
ASP.NET Web form
ASP.NET Web formASP.NET Web form
ASP.NET Web form
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 

Destaque

Dependency injection with Symfony 2
Dependency injection with Symfony 2Dependency injection with Symfony 2
Dependency injection with Symfony 2cammanderson
 
Dependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersDependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersTim Murphy
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency InjectionTheo Jungeblut
 
AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application Carlo Bonamico
 

Destaque (6)

Dependency injection with Symfony 2
Dependency injection with Symfony 2Dependency injection with Symfony 2
Dependency injection with Symfony 2
 
Dependency Injection And Ioc Containers
Dependency Injection And Ioc ContainersDependency Injection And Ioc Containers
Dependency Injection And Ioc Containers
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Clean Code II - Dependency Injection
Clean Code II - Dependency InjectionClean Code II - Dependency Injection
Clean Code II - Dependency Injection
 
IoC and Mapper in C#
IoC and Mapper in C#IoC and Mapper in C#
IoC and Mapper in C#
 
AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application AngularJS Security: defend your Single Page Application
AngularJS Security: defend your Single Page Application
 

Semelhante a Introduction to Spring's Dependency Injection

Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google GuiceKnoldus Inc.
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)hchen1
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAOAnushaNaidu
 
Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Stephan Hochdörfer
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
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 AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSYoann Gotthilf
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSUFYAN SATTAR
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpdayStephan Hochdörfer
 
Techlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinTechlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinPeter Lehto
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development GuideNitin Giri
 
Introduction to YouDebug - Scriptable Java Debugger
Introduction to YouDebug - Scriptable Java DebuggerIntroduction to YouDebug - Scriptable Java Debugger
Introduction to YouDebug - Scriptable Java DebuggerWolfgang Schell
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginnersMunir Hoque
 
Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...bjhargrave
 

Semelhante a Introduction to Spring's Dependency Injection (20)

Spring and DWR
Spring and DWRSpring and DWR
Spring and DWR
 
JEE5 New Features
JEE5 New FeaturesJEE5 New Features
JEE5 New Features
 
Introduction to Google Guice
Introduction to Google GuiceIntroduction to Google Guice
Introduction to Google Guice
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
 
Spring IOC and DAO
Spring IOC and DAOSpring IOC and DAO
Spring IOC and DAO
 
Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13Real World Dependency Injection - oscon13
Real World Dependency Injection - oscon13
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Spring training
Spring trainingSpring training
Spring training
 
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 AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
SpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptxSpringBootCompleteBootcamp.pptx
SpringBootCompleteBootcamp.pptx
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpday
 
Techlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with VaadinTechlunch - Dependency Injection with Vaadin
Techlunch - Dependency Injection with Vaadin
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
 
Introduction to YouDebug - Scriptable Java Debugger
Introduction to YouDebug - Scriptable Java DebuggerIntroduction to YouDebug - Scriptable Java Debugger
Introduction to YouDebug - Scriptable Java Debugger
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
 
Angular js for beginners
Angular js for beginnersAngular js for beginners
Angular js for beginners
 
Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...Field injection, type safe configuration, and more new goodies in Declarative...
Field injection, type safe configuration, and more new goodies in Declarative...
 
Valentine with AngularJS
Valentine with AngularJSValentine with AngularJS
Valentine with AngularJS
 

Mais de Richard Paul

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with GroovyRichard Paul
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with GebRichard Paul
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 

Mais de Richard Paul (8)

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with Groovy
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with Geb
 
Acceptance tests
Acceptance testsAcceptance tests
Acceptance tests
 
jQuery Behaviours
jQuery BehavioursjQuery Behaviours
jQuery Behaviours
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 

Último

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 

Último (20)

The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 

Introduction to Spring's Dependency Injection

  • 1. Overview of Dependency Injection in Spring Richard Paul Kiwiplan NZ Ltd 27 Mar 2009
  • 2. What is Dependency Injection Dependency Injection is a form of Inversion of Control. Also known as the Hollywood principle, quot;Don't call us, we'll call you!quot; MyService is given instances of ItemDAO and LabelDAO. MyService isn't responsible for looking up DAOs.
  • 3. Benefits of Dependency Injection Ensures configuration and usages of services are separate. Can switch implementations by simply changing the configuration. Enhances testability as mock dependencies can be injected Dependencies are easily identified No need to read the source code to see what dependencies your code talks to.
  • 4. Constructor vs Setter Injection // Constructor public class MyService implement Service { private ItemDAO itemDAO; private LabelDAO labelDAO; public MyService(ItemDAO itemDAO, LabelDAO labelDAO) { this.itemDAO = itemDAO; this.labelDAO = labelDAO; } } // Setter public class MyService implement Service { private ItemDAO itemDAO; private LabelDAO labelDAO; public setItemDAO(ItemDAO itemDAO) { this.itemDAO = itemDAO; } public setLabelDAO(LabelDAO labelDAO) { this.labelDAO = labelDAO; } }
  • 5. Constructor vs Setter Injection Both constructor and setter injection provide: Loose coupling Separation of configuration and usage Enhanced testability Constructor injection has a slight advantage (IMO) as it is upfront about what collaborators it requires. More details at: http://misko.hevery.com/2009/02/19/constructor-injection-vs-setter-injection/
  • 6. Dependency Injection in Spring There are multiple ways of setting up the dependency configuration in spring. XML Annotations JavaConfig ... It is possible to mix and match definition styles.
  • 7. XML Give myService access to labelDAO . <bean id=quot;labelDAOquot; class=quot;com.example.dao.MyLabelDAOquot;/> <!-- Constructor Injection --> <bean id=quot;myService1quot; class=quot;com.example.service.MyServiceImplquot;> <constructor-arg ref=quot;labelDAOquot;/> </bean> <!-- Setter Injection --> <bean id=quot;myService2quot; class=quot;com.example.service.MyServiceImplquot;> <property name=quot;labelDAOquot; ref=quot;labelDAOquot;/> </bean>
  • 8. XML - Multiple Files The XML configuration can be split amoung multiple files. With each file containing configuration for different areas. applicationContext.xml controllers.xml dao.xml ...
  • 9. Annotations - Example You can by-pass some of the XML configuration by using Spring's annotation support. @Service public class MyServiceImpl implement MyService { private ItemDAO itemDAO; private LabelDAO labelDAO; @Autowired public MyService(ItemDAO itemDAO, LabelDAO labelDAO) { this.itemDAO = itemDAO; this.labelDAO = labelDAO; } } @Repository public class MyItemDAO implements ItemDAO { // ... }
  • 10. Annotations - Listing There are many available annotation for wiring: @Autowired @Required @Qualifier(quot;xxxquot;) @PostConstruct/@PreDestroy @Resource - JSR-250 @Component @Service @Respository @Controller http://static.springframework.org/spring/docs/2.5.x/reference/beans. html#beans-annotation-config
  • 11. Java Config Dependency Injection with configuration done using Java. Uses annotations and replaces the XML config with Java code. @Configuration public class AppConfig { @Bean public Foo foo() { return new Foo(bar()); } @Bean public Bar bar() { return new Bar(); } }
  • 12. Alternatives The main alternative to Spring's Dependency Injection is Guice. More info available at: http://www.infoq.com/news/2007/03/guice-javaconfig Questions?