際際滷

際際滷Share a Scribd company logo
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

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