SlideShare a Scribd company logo
1 of 20
Download to read offline
Contexts and Dependency Injection (CDI)
                                                  in JEE 6




                                              Presenter
                                       Prasanna Kumar.S


JUGChennai JTech Day Sep'12
About me
A Java developer (now interested in Scala as well ...)
Active member in JUG Chennai
Creator & Co-Founder of scalaxia.com (a site which lists
  out the popular tweets about scala)
Contributed for ScalaFX project


Contact
Mail me prassee.sathian@gmail.com
Follow me @prasonscala
I blog @ prasonscala@tumblr.com
Agenda

What is & Why DI ?
What is CDI
Features of CDI
Advantages of CDI
Injecting Beans (with some EJB tit-bits !!!)
Types of Injection
Qualifiers – Built in & custom qualifiers
Scope – Types of Scopes
CDI options....
Questions
What is Dependency Injection




        PHONE ==> SIM ==> TOWER
Why Dependency Injection

user just relies (on)ly the Phone
streamlining dependent objects injection by

“Don't call your service,
let service call you”

Achieve loose coupling of objects

Well proven practise
What is CDI

 JSR 299


 Provides a unifying Dependency Injection and contextual life
cycle model for Java EE


 A completely new, richer dependency management model


 Type-safe dependency injection


 Designed for use with stateful objects (scoped objects)
Advantages of CDI
Decouple server and client
   – Using well-defined types and qualifiers
   – Allows server implementations to vary

Decouple lifecycle of collaborating components
   – Automatic contextual lifecycle
   management by the CDI runtime

Decouple orthogonal concerns (AOP)
   – Interceptors & Decorators

NO XML !!!!

Can be used in both JAVA SE and JAVA EE applications
Injecting Beans
CDI is all about DI

CDI makes use of annotations

3 Types of injection points

    Field

    Method Parameter

Methods can be

  Constructor

  Initializer

  Setter

  Producer

  Observer
Basic CDI Beans
public interface Greeting {
    public String greet(String greet);
}

@Default
public class PlainGreetingCDI implements Greeting {
    public String greet(String greet) {
        return "greetings to " + greet;
    }
}

// client code
@Inject
private Greeting greeting;
public String sayGreeting(String whomToGreet) {
        return greeting.greet(whomToGreet);
}
Qualifiers – Built in & custom quali-
                     fiers
public interface CurrencyConverter {
    public Double convert(Double howMuchToConvert);
}

@Qualifier
@Retention(RUNTIME)
@Target({ TYPE, METHOD, FIELD, PARAMETER })
public @interface CurrencyType {
    VariousCurrencies type() default VariousCurrencies.DOLLAR;
}

@CurrencyType(type = VariousCurrencies.DOLLAR)
public class DollarConverter implements CurrencyConverter {
    @Override
    public Double convert(Double howMuchToConvert) {
        return howMuchToConvert * 55;
    }
}

public enum VariousCurrencies { DOLLAR,EURO,POUNDS }
Qualifier in CDI
public interface CurrencyConverter {
    public Double convert(Double howMuchToConvert);
}

@Qualifier
@Retention(RUNTIME)
@Target({ TYPE, METHOD, FIELD, PARAMETER })
public @interface CurrencyType {
    VariousCurrencies type() default VariousCurrencies.DOLLAR;
}

@CurrencyType(type = VariousCurrencies.DOLLAR)
public class DollarConverter implements CurrencyConverter {
    @Override
    public Double convert(Double howMuchToConvert) {
        return howMuchToConvert * 55;
    }
}

public enum VariousCurrencies { DOLLAR,EURO,POUNDS }
Qualifier in CDI (Contd)
// client code
@Inject @CurrencyType
private CurrencyConverter def_converter;

@Inject @CurrencyType(type=VariousCurrencies.EURO)
private CurrencyConverter euroConverter;
Scoped Beans – Request Scope
@RequestScoped
public class RequestScopedCurrencyConverterCDI {
    private double currValue;

    @Inject
    @CurrencyType(type=VariousCurrencies.DOLLAR)
    private CurrencyConverter currencyConverter;

    // setters and getter for currencyConverter

    public double convert() {
        return currencyConverter.convert(currValue);
    }
}
Scoped Beans – Request Scope
@Stateless
public class ScopedCurrencyConverterEJB {
    @Inject private RequestScopedCurrencyConverterCDI currencyConverterCDI
    @EJB private FormattedCurrencyConverter formattedCurrencyConverter;

    public String getConvertedValue(double valueToConvert) {
        currencyConverterCDI.setCurrValue(valueToConvert);
        return formattedCurrencyConverter.getFormattedCurrency();
    }
}

@Stateless @LocalBean
public class FormattedCurrencyConverter {
    @Inject private RequestScopedCurrencyConverterCDI currencyConverter;
    public String getFormattedCurrency() {
        return "The converted "+ currencyConverter.getCurrValue() +" to " +
currencyConverter.convert();
    }
}
Scoped Beans – Request Scope
// client code
@EJB
private ScopedCurrencyConverterEJB converterEJB;
converterEJB.getConvertedValue(2) // "The converted 2.0 to 110.0"
Scoped Beans – Application Scope
@ApplicationScoped
public class ApplicationScopedCDI {
    private double currValue;

   public void setCurrValue(double currValue) {
       this.currValue = currValue;
   }

   public double getCurrValue() {
       return currValue;
   }

}
// client code
public void setValueToConvert(double value) {
        applicationScopedCurrencyConverterCDI.setCurrValue(2);
    }

   public double getValueToConvert() {
       return applicationScopedCurrencyConverterCDI.getCurrValue();
   }
Scoped Beans – Application Scope
@ApplicationScoped
public class ApplicationScopedCDI {
    private double currValue;

   public void setCurrValue(double currValue) {
       this.currValue = currValue;
   }

   public double getCurrValue() {
       return currValue;
   }

}
// client code
public void setValueToConvert(double value) {
        applicationScopedCurrencyConverterCDI.setCurrValue(2);
    }

   public double getValueToConvert() {
       return applicationScopedCurrencyConverterCDI.getCurrValue();
   }
CDI options
Reference Implementations
JBoss Weld
http://seamframework.org/Weld
Apache OpenWebBeans
http://openwebbeans.apache.org/owb/indexhtml
Caucho
http://www.caucho.com/
Supported App Containers
Jboss AS 7,GlassFish 3.1x ,Caucho, TomEE !!! &
all JEE6 containers
How do I learn / adopt
All code presented here are available under
https://github.com/prassee/JTechDayCDIExamples
You are welcome to contribute your own examples -
(Shameless sales pitch !!!!)
Project using CDI
AGORAVA project - http://agorava.org/
Feel free to contribute
JavaPassion site
http://javapassion.com/jugtalks
TomEE examples Trunk
http://tomee.apache.org/examples-trunk/index.html
Q&A

More Related Content

Similar to CDI in JEE6

Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your codevmandrychenko
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development GuideNitin Giri
 
Using Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformUsing Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformArun Gupta
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzgKristijan Jurković
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvCodelyTV
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSYoann Gotthilf
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
Make JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIMake JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIos890
 
Petcube epic battle: architecture vs product. UA Mobile 2017.
Petcube epic battle: architecture vs product. UA Mobile 2017.Petcube epic battle: architecture vs product. UA Mobile 2017.
Petcube epic battle: architecture vs product. UA Mobile 2017.UA Mobile
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java DevelopersYakov Fain
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodeSWIFTotter Solutions
 

Similar to CDI in JEE6 (20)

Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
Refactoring - improving the smell of your code
Refactoring - improving the smell of your codeRefactoring - improving the smell of your code
Refactoring - improving the smell of your code
 
Angular workshop - Full Development Guide
Angular workshop - Full Development GuideAngular workshop - Full Development Guide
Angular workshop - Full Development Guide
 
Using Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformUsing Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 Platform
 
Hexagonal architecture
Hexagonal architectureHexagonal architecture
Hexagonal architecture
 
AngularJs Crash Course
AngularJs Crash CourseAngularJs Crash Course
AngularJs Crash Course
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzg
 
From framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytvFrom framework coupled code to #microservices through #DDD /by @codelytv
From framework coupled code to #microservices through #DDD /by @codelytv
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
 
Make JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIMake JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODI
 
Petcube epic battle: architecture vs product. UA Mobile 2017.
Petcube epic battle: architecture vs product. UA Mobile 2017.Petcube epic battle: architecture vs product. UA Mobile 2017.
Petcube epic battle: architecture vs product. UA Mobile 2017.
 
Angular js-crash-course
Angular js-crash-courseAngular js-crash-course
Angular js-crash-course
 
Dart for Java Developers
Dart for Java DevelopersDart for Java Developers
Dart for Java Developers
 
PHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better CodePHP: 4 Design Patterns to Make Better Code
PHP: 4 Design Patterns to Make Better Code
 

More from PrasannaKumar Sathyanarayanan (10)

Akka introtalk HyScala DEC 2016
Akka introtalk HyScala DEC 2016Akka introtalk HyScala DEC 2016
Akka introtalk HyScala DEC 2016
 
Akka fsm presentation
Akka fsm presentationAkka fsm presentation
Akka fsm presentation
 
Cps (continuation passing style) in scala
Cps (continuation passing style) in scalaCps (continuation passing style) in scala
Cps (continuation passing style) in scala
 
Introduction to akka chense
Introduction to akka   chenseIntroduction to akka   chense
Introduction to akka chense
 
Finagle - an intro to rpc & a sync programming in jvm
Finagle - an intro to rpc & a sync programming in jvmFinagle - an intro to rpc & a sync programming in jvm
Finagle - an intro to rpc & a sync programming in jvm
 
Websocket,JSON in JEE7
Websocket,JSON in JEE7Websocket,JSON in JEE7
Websocket,JSON in JEE7
 
Scala Introduction with play - for my CSS nerds
Scala Introduction with play - for my CSS nerdsScala Introduction with play - for my CSS nerds
Scala Introduction with play - for my CSS nerds
 
Ejb3.1
Ejb3.1Ejb3.1
Ejb3.1
 
Producer consumerproblem
Producer consumerproblemProducer consumerproblem
Producer consumerproblem
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 

Recently uploaded

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 

CDI in JEE6

  • 1. Contexts and Dependency Injection (CDI) in JEE 6 Presenter Prasanna Kumar.S JUGChennai JTech Day Sep'12
  • 2. About me A Java developer (now interested in Scala as well ...) Active member in JUG Chennai Creator & Co-Founder of scalaxia.com (a site which lists out the popular tweets about scala) Contributed for ScalaFX project Contact Mail me prassee.sathian@gmail.com Follow me @prasonscala I blog @ prasonscala@tumblr.com
  • 3. Agenda What is & Why DI ? What is CDI Features of CDI Advantages of CDI Injecting Beans (with some EJB tit-bits !!!) Types of Injection Qualifiers – Built in & custom qualifiers Scope – Types of Scopes CDI options.... Questions
  • 4. What is Dependency Injection PHONE ==> SIM ==> TOWER
  • 5. Why Dependency Injection user just relies (on)ly the Phone streamlining dependent objects injection by “Don't call your service, let service call you” Achieve loose coupling of objects Well proven practise
  • 6. What is CDI  JSR 299  Provides a unifying Dependency Injection and contextual life cycle model for Java EE  A completely new, richer dependency management model  Type-safe dependency injection  Designed for use with stateful objects (scoped objects)
  • 7. Advantages of CDI Decouple server and client – Using well-defined types and qualifiers – Allows server implementations to vary Decouple lifecycle of collaborating components – Automatic contextual lifecycle management by the CDI runtime Decouple orthogonal concerns (AOP) – Interceptors & Decorators NO XML !!!! Can be used in both JAVA SE and JAVA EE applications
  • 8. Injecting Beans CDI is all about DI CDI makes use of annotations 3 Types of injection points  Field  Method Parameter Methods can be  Constructor  Initializer  Setter  Producer  Observer
  • 9. Basic CDI Beans public interface Greeting { public String greet(String greet); } @Default public class PlainGreetingCDI implements Greeting { public String greet(String greet) { return "greetings to " + greet; } } // client code @Inject private Greeting greeting; public String sayGreeting(String whomToGreet) { return greeting.greet(whomToGreet); }
  • 10. Qualifiers – Built in & custom quali- fiers public interface CurrencyConverter { public Double convert(Double howMuchToConvert); } @Qualifier @Retention(RUNTIME) @Target({ TYPE, METHOD, FIELD, PARAMETER }) public @interface CurrencyType { VariousCurrencies type() default VariousCurrencies.DOLLAR; } @CurrencyType(type = VariousCurrencies.DOLLAR) public class DollarConverter implements CurrencyConverter { @Override public Double convert(Double howMuchToConvert) { return howMuchToConvert * 55; } } public enum VariousCurrencies { DOLLAR,EURO,POUNDS }
  • 11. Qualifier in CDI public interface CurrencyConverter { public Double convert(Double howMuchToConvert); } @Qualifier @Retention(RUNTIME) @Target({ TYPE, METHOD, FIELD, PARAMETER }) public @interface CurrencyType { VariousCurrencies type() default VariousCurrencies.DOLLAR; } @CurrencyType(type = VariousCurrencies.DOLLAR) public class DollarConverter implements CurrencyConverter { @Override public Double convert(Double howMuchToConvert) { return howMuchToConvert * 55; } } public enum VariousCurrencies { DOLLAR,EURO,POUNDS }
  • 12. Qualifier in CDI (Contd) // client code @Inject @CurrencyType private CurrencyConverter def_converter; @Inject @CurrencyType(type=VariousCurrencies.EURO) private CurrencyConverter euroConverter;
  • 13. Scoped Beans – Request Scope @RequestScoped public class RequestScopedCurrencyConverterCDI { private double currValue; @Inject @CurrencyType(type=VariousCurrencies.DOLLAR) private CurrencyConverter currencyConverter; // setters and getter for currencyConverter public double convert() { return currencyConverter.convert(currValue); } }
  • 14. Scoped Beans – Request Scope @Stateless public class ScopedCurrencyConverterEJB { @Inject private RequestScopedCurrencyConverterCDI currencyConverterCDI @EJB private FormattedCurrencyConverter formattedCurrencyConverter; public String getConvertedValue(double valueToConvert) { currencyConverterCDI.setCurrValue(valueToConvert); return formattedCurrencyConverter.getFormattedCurrency(); } } @Stateless @LocalBean public class FormattedCurrencyConverter { @Inject private RequestScopedCurrencyConverterCDI currencyConverter; public String getFormattedCurrency() { return "The converted "+ currencyConverter.getCurrValue() +" to " + currencyConverter.convert(); } }
  • 15. Scoped Beans – Request Scope // client code @EJB private ScopedCurrencyConverterEJB converterEJB; converterEJB.getConvertedValue(2) // "The converted 2.0 to 110.0"
  • 16. Scoped Beans – Application Scope @ApplicationScoped public class ApplicationScopedCDI { private double currValue; public void setCurrValue(double currValue) { this.currValue = currValue; } public double getCurrValue() { return currValue; } } // client code public void setValueToConvert(double value) { applicationScopedCurrencyConverterCDI.setCurrValue(2); } public double getValueToConvert() { return applicationScopedCurrencyConverterCDI.getCurrValue(); }
  • 17. Scoped Beans – Application Scope @ApplicationScoped public class ApplicationScopedCDI { private double currValue; public void setCurrValue(double currValue) { this.currValue = currValue; } public double getCurrValue() { return currValue; } } // client code public void setValueToConvert(double value) { applicationScopedCurrencyConverterCDI.setCurrValue(2); } public double getValueToConvert() { return applicationScopedCurrencyConverterCDI.getCurrValue(); }
  • 18. CDI options Reference Implementations JBoss Weld http://seamframework.org/Weld Apache OpenWebBeans http://openwebbeans.apache.org/owb/indexhtml Caucho http://www.caucho.com/ Supported App Containers Jboss AS 7,GlassFish 3.1x ,Caucho, TomEE !!! & all JEE6 containers
  • 19. How do I learn / adopt All code presented here are available under https://github.com/prassee/JTechDayCDIExamples You are welcome to contribute your own examples - (Shameless sales pitch !!!!) Project using CDI AGORAVA project - http://agorava.org/ Feel free to contribute JavaPassion site http://javapassion.com/jugtalks TomEE examples Trunk http://tomee.apache.org/examples-trunk/index.html
  • 20. Q&A