SlideShare a Scribd company logo
1 of 31
Download to read offline
CDI .

Dependency Injection in JEE6


           jens.augustsson@redpill-linpro.com




Consulting ● Development ● IT Operations ● Training ● Support ● Products
Today.


              1. What it is
              2. Features
              3. Advices




Consulting ● Development ● IT Operations ● Training ● Support ● Products
next...




               1. What it is




Consulting ● Development ● IT Operations ● Training ● Support ● Products
Example.
public class TextTranslator {

   private final SentenceParser sentenceParser;
   private final Translator sentenceTranslator;

   @Inject
   public TextTranslator(SentenceParser sentenceParser, 
               Translator sentenceTranslator) {

      this.sentenceParser = sentenceParser;
      this.sentenceTranslator = sentenceTranslator;
   }

   public String translate(String text) {
      StringBuilder sb = new StringBuilder();
      for (String sentence: sentenceParser.parse(text)) {
          sb.append(sentenceTranslator.translate(sentence));
      }
      return sb.toString();
   }
}




               Consulting ● Development ● IT Operations ● Training ● Support ● Products
Example - 2.
@Stateless

public class SentenceTranslator implements Translator {

   public String translate(String sentence) { ... }

}

public class SentenceParser {

   public List<String> parse(String text) { ... }

}



Injection of: Managed Bean, EJB session beans
Injection to: MDB, interceptor, Servlet, JAX-WS SE, JSP (tag h / ev lis)



         Consulting ● Development ● IT Operations ● Training ● Support ● Products
Martin Fowler.
      Coined the term ”Dependency Injection”



                «The fundamental choice is between
           Service Locator and Dependency Injection»

            http://martinfowler.com/articles/injection.html




«Inversion of Control» ... «The Hollywood principle»


      Consulting ● Development ● IT Operations ● Training ● Support ● Products
CDI - JSR299.



”Context and Dependency Injection for the Java EE Platform”



                      «Loose coupling, strong typing»




            Consulting ● Development ● IT Operations ● Training ● Support ● Products
but...




               Why care?




Consulting ● Development ● IT Operations ● Training ● Support ● Products
JEE5 DI features.
Resource injection in JEE5
✔   @EJB, @Resource, @PersistenceContext,
    @PersistenceUnit
✔   Servlets, JSF backing beans and other EJBs




Problems
✔   Cannot inject EJBs into Struts Actions
✔   Cannot inject DAOs or helper classes that
    were not written as EJBs
✔   Hard to integrate anything but strictly
    business components




           Consulting ● Development ● IT Operations ● Training ● Support ● Products
Alternative DI frameworks.
PicoContainer
    ✔   Early one

HiveMind
    ✔   Howard Lewis Ship & Tapestry




Spring Core
✔       The de facto standard


Seam 2
 ✔      By the Hibernate Team

Guice
 ✔      Crazy Bob Lee @ Google



                    Consulting ● Development ● IT Operations ● Training ● Support ● Products
but I've heard the term.....
                                                                              CDI
   WebBeans
                        old name for...           new name for...

                                     JSR-299
             implements...                                 inspired...
                                                                                  Seam 2
Weld
                               part of...

                                            includes...
 uses...              Java EE 6
                                                                                      D4J
                                                           name for...
Seam 3                                          JSR-330

                                  created by...              created by...

                                                                         Spring Core
                         Guice

           Consulting ● Development ● IT Operations ● Training ● Support ● Products
next...




               2. CDI Features




Consulting ● Development ● IT Operations ● Training ● Support ● Products
Injection points.
Class constructor              public class Checkout {      
                                  private final ShoppingCart cart;

                                  @Inject
                                  public Checkout(ShoppingCart cart) {
                                     this.cart = cart;
                                  }
                               }


Initializer method            public class Checkout {
                                 private ShoppingCart cart;

                                   @Inject
                                   void setShoppingCart(ShoppingCart cart) {
                                      this.cart = cart;
                                   }
                              }


Direct field                  public class Checkout {
                                 private @Inject ShoppingCart cart;
                              }



        Consulting ● Development ● IT Operations ● Training ● Support ● Products
Bean types.
A user-defined class or interface
In a JEE module with a /META-INF/beans.xml



         public class BookShop

                 extends Business

                 implements Shop<Book>, Auditable {

             ...

         }




         ...but «there can be only one»...



       Consulting ● Development ● IT Operations ● Training ● Support ● Products
Non-default qualifiers.
Custom annotations links...
  @Qualifier
  @Retention(RUNTIME)
  @Target({TYPE, METHOD, FIELD, PARAMETER})
  public @interface Asynchronous {}



...the qualified bean...
  @Asynchronous
  public class AsynchronousPaymentProcessor implements PaymentProcessor {
    public void process(Payment payment) { ... }
  }



...to declared injection points.
  @Inject @Asynchronous PaymentProcessor asyncPaymentProcessor;
  @Inject @Synchronous PaymentProcessor syncPaymentProcessor;


          Consulting ● Development ● IT Operations ● Training ● Support ● Products
Producer methods.
    Run time qualifier

public PaymentAction {
    @Inject @Preferred PaymentStrategy paymentStrategy;
    ...
}


@Singleton @Managed
public PaymentServiceBean imlements PaymentService {

    PaymentStrategy paymentStrategy = PaymentStrategy.CREDIT_CARD;

     @Produces @Preferred @SessionScoped
     public PaymentStrategy getPaymentStrategy(CreditCardPaymentStrategy ccps,
                                           CheckPaymentStrategy cps,
                                           PayPalPaymentStrategy ppps) {
        switch (paymentStrategy) {
            case CREDIT_CARD: return ccps;
            case CHEQUE: return cps;
            case PAYPAL: return ppps;
       default: return null;
    }
}

               Consulting ● Development ● IT Operations ● Training ● Support ● Products
Scopes and Contexts.
Scope determines...
✔   When a new instance of any bean with that scope is created
✔   When an existing instance of any bean with that scope is destroyed
✔   Which injected references refer to any instance of a bean with that scope
✔   CDI features an extensible context model




Built-in scopes
✔   (@Dependent)
✔   @RequestScoped
✔   @SessionScoped
✔   @ApplicationScoped
✔   @ConversationScoped




           Consulting ● Development ● IT Operations ● Training ● Support ● Products
Conversation Scope.
@ConversationScoped @Stateful
public class OrderBuilder {
   private Order order;
   private @Inject Conversation conversation;
   private @PersistenceContext EntityManager em;

   public Order createOrder() {
      order = new Order();
      conversation.begin();
      return order;
   }
   
   public void addLineItem(Product product, int quantity) {
      order.add(new LineItem(product, quantity));
   }

   public void saveOrder() {
      em.persist(order);
      conversation.end();
   }

   @Remove
   public void destroy() {}
}


             Consulting ● Development ● IT Operations ● Training ● Support ● Products
Interceptors.


business method interception
lifecycle callback interception
timeout method interception (ejb3)




  Consulting ● Development ● IT Operations ● Training ● Support ● Products
Interceptors - 2.

   Binding


@InterceptorBinding
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface MySecurity {}




public class ShoppingCart {
  @MySecurity public void checkout() { ... }
}




                 Consulting ● Development ● IT Operations ● Training ● Support ● Products
Interceptors - 3.

    Implementation - business method:
@MySecurity @Interceptor
public class MySecurityInterceptor {

    @AroundInvoke
    public Object manageSecurity(InvocationContext ctx) throws Exception { ... }

}




    Implementation - lifecycle: @PostConstruct, @PreDestroy...



    Implementation - timeout: @AroundTimeout



             Consulting ● Development ● IT Operations ● Training ● Support ● Products
Decorators .
    Interceptors capture orthogonal application concerns
                 §
    The reverse is true of decorators
@Decorator
public abstract class LargeTransactionDecorator implements Account {

    @Inject @Delegate @Any Account account;
    @PersistenceContext EntityManager em;

    public void withdraw(BigDecimal amount) {
      account.withdraw(amount);
      if ( amount.compareTo(LARGE_AMOUNT)>0 ) {
         em.persist( new LoggedWithdrawl(amount) );
      }
    }

    public void deposit(BigDecimal amount);
      account.deposit(amount);
      if ( amount.compareTo(LARGE_AMOUNT)>0 ) {
         em.persist( new LoggedDeposit(amount) );
      }
    }

}                 Consulting ● Development ● IT Operations ● Training ● Support ● Products
Events.
    Become observable....
         @Inject @Any Event<Document> documentEvent;
                      ...

         documentEvent.fire(document);



    Become observer....

      public void onAnyDocumentEvent(@Observes Document document) { ... }


    Many conditional observations...
public void refreshOnDocumentUpdate(@Observes(receive = IF_EXISTS) @Updated Document d

public void addProduct(@Observes(during = AFTER_SUCCESS) @Created Product product) { .. }



                 Consulting ● Development ● IT Operations ● Training ● Support ● Products
Predefine scope and interceptors           Stereotypes.
Declare                                                    Predefined by CDI:
                                                           @Interceptor, @Decorator
  @Stateless                                               and @Model
  @Transactional(requiresNew=true)
  @Secure
  @Target(TYPE)                                              @Named
  @Retention(RUNTIME)                                        @RequestScoped
  @Stereotype                                                @Documented
  public @interface BusinessLogic {}                         @Stereotype
                                                             @Target(TYPE,METHOD,FIELD)
                                                             @Retention(RUNTIME)
Use                                                          public @interface Model {}
@BusinessLogic
public class UserService { ... }




                Consulting ● Development ● IT Operations ● Training ● Support ● Products
JEE comp env resources.
@Produces @Resource(lookup="java:global/env/jdbc/CustomerDatasource")
@CustomerDatabase Datasource customerDatabase;




@Produces @PersistenceUnit(unitName="CustomerDatabase")
@CustomerDatabase EntityManagerFactory customerDatabasePersistenceUnit;



@Produces @WebServiceRef(lookup="java:app/service/Catalog")
Catalog catalog;


 @Produces @EJB(ejbLink="../their.jar#PaymentService")
 PaymentService paymentService;




          Consulting ● Development ● IT Operations ● Training ● Support ● Products
next...




               3. Advices




Consulting ● Development ● IT Operations ● Training ● Support ● Products
Similarities – with Seam2.
Spring IoC users: CDI more type-safe and
annotation-driven




Guice users: CDI more geared towards
enterprise development




Seam users: CDI has a lot more advanced
features




 Consulting ● Development ● IT Operations ● Training ● Support ● Products
Similarities – with D4J .
        Only five annotations!

        @Inject
        @Qualifier
        @Named
        @Scope
        @Singleton




Consulting ● Development ● IT Operations ● Training ● Support ● Products
Personal experiences.

Good stuff
      Seam improvement – no outjection, method-time injection etc.
      Great for use with other frameworks – like jBPM
      XML-hell is /actually/ gone




Be careful
      Start off with managed beans – switch when needed
      Avoid injection from ”thinner” context – use @Dependent
      Weld documentation not finished
      Avoid ”upgrade” JBoss AS 5.x
      XML Configuration in Seam 3 Module
      Annotation Frustration...

          Consulting ● Development ● IT Operations ● Training ● Support ● Products
Get started!.
    In JBoss 6.0.0.Final (Weld 1.1.0.Beta2)

    In GlassFish Server 3.1 (Weld 1.1.0.Final)

    Embed Weld in Tomcat, Jetty... Android almost :-)




And read more!

     Dan Allens slideshare: Google ”Dan Allen slideshare cdi”
     Gavin King and Bob Lee flamewar: Google ”Gavin King Bob Lee jsr"




        Consulting ● Development ● IT Operations ● Training ● Support ● Products
End.



    jens.augustsson@redpill-linpro.com




Consulting ● Development ● IT Operations ● Training ● Support ● Products

More Related Content

What's hot

Why should i switch to Java SE 7
Why should i switch to Java SE 7Why should i switch to Java SE 7
Why should i switch to Java SE 7
Vinay H G
 
Cloud Best Practices
Cloud Best PracticesCloud Best Practices
Cloud Best Practices
Eric Bottard
 
Adopting Agile Tools & Methods In A Legacy Context
Adopting Agile Tools & Methods In A Legacy ContextAdopting Agile Tools & Methods In A Legacy Context
Adopting Agile Tools & Methods In A Legacy Context
Xavier Warzee
 
10 generics a-4_in_1
10 generics a-4_in_110 generics a-4_in_1
10 generics a-4_in_1
arasforever
 
Tdd and a new paradigm for hardware verification
Tdd and a new paradigm for hardware verificationTdd and a new paradigm for hardware verification
Tdd and a new paradigm for hardware verification
drewz lin
 

What's hot (20)

Lesson2 software process_contd2
Lesson2 software process_contd2Lesson2 software process_contd2
Lesson2 software process_contd2
 
PL/SQL Development
PL/SQL DevelopmentPL/SQL Development
PL/SQL Development
 
Dayal rtp q2_07
Dayal rtp q2_07Dayal rtp q2_07
Dayal rtp q2_07
 
Glidein startup Internals and Glidein configuration - glideinWMS Training Jan...
Glidein startup Internals and Glidein configuration - glideinWMS Training Jan...Glidein startup Internals and Glidein configuration - glideinWMS Training Jan...
Glidein startup Internals and Glidein configuration - glideinWMS Training Jan...
 
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
OSGi-enabled Java EE Applications using GlassFish at JCertif 2011
 
Running your Java EE applications in the Cloud
Running your Java EE applications in the CloudRunning your Java EE applications in the Cloud
Running your Java EE applications in the Cloud
 
GlassFish v3, OSGi Equinox Felix
GlassFish v3, OSGi Equinox FelixGlassFish v3, OSGi Equinox Felix
GlassFish v3, OSGi Equinox Felix
 
Cambridge Consultants Innovation Day 2012: Minimising risk and delay for comp...
Cambridge Consultants Innovation Day 2012: Minimising risk and delay for comp...Cambridge Consultants Innovation Day 2012: Minimising risk and delay for comp...
Cambridge Consultants Innovation Day 2012: Minimising risk and delay for comp...
 
Modules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module SystemModules all the way down: OSGi and the Java Platform Module System
Modules all the way down: OSGi and the Java Platform Module System
 
Why should i switch to Java SE 7
Why should i switch to Java SE 7Why should i switch to Java SE 7
Why should i switch to Java SE 7
 
Airbus Internship Presentation 2012
Airbus Internship Presentation 2012Airbus Internship Presentation 2012
Airbus Internship Presentation 2012
 
Glidein internals
Glidein internalsGlidein internals
Glidein internals
 
Cloud Best Practices
Cloud Best PracticesCloud Best Practices
Cloud Best Practices
 
Adopting Agile Tools & Methods In A Legacy Context
Adopting Agile Tools & Methods In A Legacy ContextAdopting Agile Tools & Methods In A Legacy Context
Adopting Agile Tools & Methods In A Legacy Context
 
10 generics a-4_in_1
10 generics a-4_in_110 generics a-4_in_1
10 generics a-4_in_1
 
glideinWMS Frontend Internals - glideinWMS Training Jan 2012
glideinWMS Frontend Internals - glideinWMS Training Jan 2012glideinWMS Frontend Internals - glideinWMS Training Jan 2012
glideinWMS Frontend Internals - glideinWMS Training Jan 2012
 
Tdd and a new paradigm for hardware verification
Tdd and a new paradigm for hardware verificationTdd and a new paradigm for hardware verification
Tdd and a new paradigm for hardware verification
 
Java Summit Chennai: JAX-RS 2.0
Java Summit Chennai: JAX-RS 2.0Java Summit Chennai: JAX-RS 2.0
Java Summit Chennai: JAX-RS 2.0
 
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
The Java EE 7 Platform: Productivity & HTML5 at JavaOne Latin America 2012
 
Running your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the CloudRunning your Java EE 6 applications in the Cloud
Running your Java EE 6 applications in the Cloud
 

Viewers also liked

Viewers also liked (6)

CDI and Weld
CDI and WeldCDI and Weld
CDI and Weld
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
Going Further with CDI 1.2
Going Further with CDI 1.2Going Further with CDI 1.2
Going Further with CDI 1.2
 
Adopt a JSR: CDI 2.0 at Devoxx UK
Adopt a JSR: CDI 2.0 at Devoxx UKAdopt a JSR: CDI 2.0 at Devoxx UK
Adopt a JSR: CDI 2.0 at Devoxx UK
 
Bean validation 1.1
Bean validation 1.1Bean validation 1.1
Bean validation 1.1
 
Java EE vs Spring Framework
Java  EE vs Spring Framework Java  EE vs Spring Framework
Java EE vs Spring Framework
 

Similar to CDI and Weld

Briforum2013 applicationpackagingsmackdown public
Briforum2013 applicationpackagingsmackdown publicBriforum2013 applicationpackagingsmackdown public
Briforum2013 applicationpackagingsmackdown public
Kevin Kaminski
 
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating FrameworksJSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
Mario Heiderich
 

Similar to CDI and Weld (20)

Tips for Building your First XPages Java Application
Tips for Building your First XPages Java ApplicationTips for Building your First XPages Java Application
Tips for Building your First XPages Java Application
 
Moving to tdd bdd
Moving to tdd bddMoving to tdd bdd
Moving to tdd bdd
 
Extending CMS Made Simple
Extending CMS Made SimpleExtending CMS Made Simple
Extending CMS Made Simple
 
Open Source ERP Technologies for Java Developers
Open Source ERP Technologies for Java DevelopersOpen Source ERP Technologies for Java Developers
Open Source ERP Technologies for Java Developers
 
Moving away from legacy code with BDD
Moving away from legacy code with BDDMoving away from legacy code with BDD
Moving away from legacy code with BDD
 
The Anchor Store: Four Confluence Examples to Root Your Deployment
The Anchor Store: Four Confluence Examples to Root Your DeploymentThe Anchor Store: Four Confluence Examples to Root Your Deployment
The Anchor Store: Four Confluence Examples to Root Your Deployment
 
Prashant technical practices-tdd for xebia event
Prashant   technical practices-tdd for xebia eventPrashant   technical practices-tdd for xebia event
Prashant technical practices-tdd for xebia event
 
DS, BP, EJB, CDI, WTF!? - Graham Charters
DS, BP, EJB, CDI, WTF!? - Graham ChartersDS, BP, EJB, CDI, WTF!? - Graham Charters
DS, BP, EJB, CDI, WTF!? - Graham Charters
 
Luiz Fernando Testa Contador - Aplicando DevOps em grandes corporações
Luiz Fernando Testa Contador - Aplicando DevOps em grandes corporaçõesLuiz Fernando Testa Contador - Aplicando DevOps em grandes corporações
Luiz Fernando Testa Contador - Aplicando DevOps em grandes corporações
 
JS Fest 2018. Никита Галкин. Микросервисная архитектура с переиспользуемыми к...
JS Fest 2018. Никита Галкин. Микросервисная архитектура с переиспользуемыми к...JS Fest 2018. Никита Галкин. Микросервисная архитектура с переиспользуемыми к...
JS Fest 2018. Никита Галкин. Микросервисная архитектура с переиспользуемыми к...
 
Venu-Sage X3-resume
Venu-Sage  X3-resumeVenu-Sage  X3-resume
Venu-Sage X3-resume
 
Apache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI ToolboxApache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI Toolbox
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
From prototype to production - The journey of re-designing SmartUp.io
From prototype to production - The journey of re-designing SmartUp.ioFrom prototype to production - The journey of re-designing SmartUp.io
From prototype to production - The journey of re-designing SmartUp.io
 
Gui Report Studio in java
Gui Report Studio in javaGui Report Studio in java
Gui Report Studio in java
 
Briforum2013 applicationpackagingsmackdown public
Briforum2013 applicationpackagingsmackdown publicBriforum2013 applicationpackagingsmackdown public
Briforum2013 applicationpackagingsmackdown public
 
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating FrameworksJSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
JSMVCOMFG - To sternly look at JavaScript MVC and Templating Frameworks
 
Product? What Product?
Product? What Product?Product? What Product?
Product? What Product?
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
 
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
 

CDI and Weld

  • 1. CDI . Dependency Injection in JEE6 jens.augustsson@redpill-linpro.com Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 2. Today. 1. What it is 2. Features 3. Advices Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 3. next... 1. What it is Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 4. Example. public class TextTranslator {    private final SentenceParser sentenceParser;    private final Translator sentenceTranslator;    @Inject    public TextTranslator(SentenceParser sentenceParser,  Translator sentenceTranslator) {       this.sentenceParser = sentenceParser;       this.sentenceTranslator = sentenceTranslator;    }    public String translate(String text) {       StringBuilder sb = new StringBuilder();       for (String sentence: sentenceParser.parse(text)) {           sb.append(sentenceTranslator.translate(sentence));       }       return sb.toString();    } } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 5. Example - 2. @Stateless public class SentenceTranslator implements Translator {    public String translate(String sentence) { ... } } public class SentenceParser {    public List<String> parse(String text) { ... } } Injection of: Managed Bean, EJB session beans Injection to: MDB, interceptor, Servlet, JAX-WS SE, JSP (tag h / ev lis) Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 6. Martin Fowler. Coined the term ”Dependency Injection” «The fundamental choice is between Service Locator and Dependency Injection» http://martinfowler.com/articles/injection.html «Inversion of Control» ... «The Hollywood principle» Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 7. CDI - JSR299. ”Context and Dependency Injection for the Java EE Platform” «Loose coupling, strong typing» Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 8. but... Why care? Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 9. JEE5 DI features. Resource injection in JEE5 ✔ @EJB, @Resource, @PersistenceContext, @PersistenceUnit ✔ Servlets, JSF backing beans and other EJBs Problems ✔ Cannot inject EJBs into Struts Actions ✔ Cannot inject DAOs or helper classes that were not written as EJBs ✔ Hard to integrate anything but strictly business components Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 10. Alternative DI frameworks. PicoContainer ✔ Early one HiveMind ✔ Howard Lewis Ship & Tapestry Spring Core ✔ The de facto standard Seam 2 ✔ By the Hibernate Team Guice ✔ Crazy Bob Lee @ Google Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 11. but I've heard the term..... CDI WebBeans old name for... new name for... JSR-299 implements... inspired... Seam 2 Weld part of... includes... uses... Java EE 6 D4J name for... Seam 3 JSR-330 created by... created by... Spring Core Guice Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 12. next... 2. CDI Features Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 13. Injection points. Class constructor public class Checkout {          private final ShoppingCart cart;    @Inject    public Checkout(ShoppingCart cart) {       this.cart = cart;    } } Initializer method public class Checkout { private ShoppingCart cart; @Inject void setShoppingCart(ShoppingCart cart) { this.cart = cart; } } Direct field public class Checkout { private @Inject ShoppingCart cart; } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 14. Bean types. A user-defined class or interface In a JEE module with a /META-INF/beans.xml public class BookShop extends Business implements Shop<Book>, Auditable { ... } ...but «there can be only one»... Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 15. Non-default qualifiers. Custom annotations links... @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface Asynchronous {} ...the qualified bean... @Asynchronous public class AsynchronousPaymentProcessor implements PaymentProcessor { public void process(Payment payment) { ... } } ...to declared injection points. @Inject @Asynchronous PaymentProcessor asyncPaymentProcessor; @Inject @Synchronous PaymentProcessor syncPaymentProcessor; Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 16. Producer methods. Run time qualifier public PaymentAction { @Inject @Preferred PaymentStrategy paymentStrategy; ... } @Singleton @Managed public PaymentServiceBean imlements PaymentService { PaymentStrategy paymentStrategy = PaymentStrategy.CREDIT_CARD; @Produces @Preferred @SessionScoped public PaymentStrategy getPaymentStrategy(CreditCardPaymentStrategy ccps, CheckPaymentStrategy cps, PayPalPaymentStrategy ppps) { switch (paymentStrategy) { case CREDIT_CARD: return ccps; case CHEQUE: return cps; case PAYPAL: return ppps; default: return null; } } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 17. Scopes and Contexts. Scope determines... ✔ When a new instance of any bean with that scope is created ✔ When an existing instance of any bean with that scope is destroyed ✔ Which injected references refer to any instance of a bean with that scope ✔ CDI features an extensible context model Built-in scopes ✔ (@Dependent) ✔ @RequestScoped ✔ @SessionScoped ✔ @ApplicationScoped ✔ @ConversationScoped Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 19. Interceptors. business method interception lifecycle callback interception timeout method interception (ejb3) Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 20. Interceptors - 2. Binding @InterceptorBinding @Target({METHOD, TYPE}) @Retention(RUNTIME) public @interface MySecurity {} public class ShoppingCart { @MySecurity public void checkout() { ... } } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 21. Interceptors - 3. Implementation - business method: @MySecurity @Interceptor public class MySecurityInterceptor { @AroundInvoke public Object manageSecurity(InvocationContext ctx) throws Exception { ... } } Implementation - lifecycle: @PostConstruct, @PreDestroy... Implementation - timeout: @AroundTimeout Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 22. Decorators . Interceptors capture orthogonal application concerns § The reverse is true of decorators @Decorator public abstract class LargeTransactionDecorator implements Account { @Inject @Delegate @Any Account account; @PersistenceContext EntityManager em; public void withdraw(BigDecimal amount) { account.withdraw(amount); if ( amount.compareTo(LARGE_AMOUNT)>0 ) { em.persist( new LoggedWithdrawl(amount) ); } } public void deposit(BigDecimal amount); account.deposit(amount); if ( amount.compareTo(LARGE_AMOUNT)>0 ) { em.persist( new LoggedDeposit(amount) ); } } } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 23. Events. Become observable.... @Inject @Any Event<Document> documentEvent; ... documentEvent.fire(document); Become observer.... public void onAnyDocumentEvent(@Observes Document document) { ... } Many conditional observations... public void refreshOnDocumentUpdate(@Observes(receive = IF_EXISTS) @Updated Document d public void addProduct(@Observes(during = AFTER_SUCCESS) @Created Product product) { .. } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 24. Predefine scope and interceptors Stereotypes. Declare Predefined by CDI: @Interceptor, @Decorator @Stateless and @Model @Transactional(requiresNew=true) @Secure @Target(TYPE) @Named @Retention(RUNTIME) @RequestScoped @Stereotype @Documented public @interface BusinessLogic {} @Stereotype @Target(TYPE,METHOD,FIELD) @Retention(RUNTIME) Use public @interface Model {} @BusinessLogic public class UserService { ... } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 25. JEE comp env resources. @Produces @Resource(lookup="java:global/env/jdbc/CustomerDatasource") @CustomerDatabase Datasource customerDatabase; @Produces @PersistenceUnit(unitName="CustomerDatabase") @CustomerDatabase EntityManagerFactory customerDatabasePersistenceUnit; @Produces @WebServiceRef(lookup="java:app/service/Catalog") Catalog catalog; @Produces @EJB(ejbLink="../their.jar#PaymentService") PaymentService paymentService; Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 26. next... 3. Advices Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 27. Similarities – with Seam2. Spring IoC users: CDI more type-safe and annotation-driven Guice users: CDI more geared towards enterprise development Seam users: CDI has a lot more advanced features Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 28. Similarities – with D4J . Only five annotations! @Inject @Qualifier @Named @Scope @Singleton Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 29. Personal experiences. Good stuff Seam improvement – no outjection, method-time injection etc. Great for use with other frameworks – like jBPM XML-hell is /actually/ gone Be careful Start off with managed beans – switch when needed Avoid injection from ”thinner” context – use @Dependent Weld documentation not finished Avoid ”upgrade” JBoss AS 5.x XML Configuration in Seam 3 Module Annotation Frustration... Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 30. Get started!. In JBoss 6.0.0.Final (Weld 1.1.0.Beta2) In GlassFish Server 3.1 (Weld 1.1.0.Final) Embed Weld in Tomcat, Jetty... Android almost :-) And read more! Dan Allens slideshare: Google ”Dan Allen slideshare cdi” Gavin King and Bob Lee flamewar: Google ”Gavin King Bob Lee jsr" Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 31. End. jens.augustsson@redpill-linpro.com Consulting ● Development ● IT Operations ● Training ● Support ● Products