SlideShare a Scribd company logo
1 of 23
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
«but I've heard.....»
                                                                              CDI
   WebBeans
                       old name for...          new name for...
                                                                                      Hibernate
                                   JSR-299                                      standardized
            implements...
Weld
                          part of...                                           JPA
                                                inspired...
                                 includes...                       next project...
 uses...       Java EE 6
                                                              Seam 2

Seam 3                         JSR-330 created by...                 Spring Core
                     name for...               created by...

                                                               Guice
                D4J

           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
Injectable bean types.
   A user-defined class or interface
   In a JEE module with a /META-INF/beans.xml

                                    public class CreditCardPaymentService
            declare                       implements PaymentService {
                                       ...
                                    }

     use



...                                                        ...
@Inject                                       or?          @Inject
CreditCardPaymentService ps;                               PaymentService ps;
...                                                        ...


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

              Consulting ● Development ● IT Operations ● Training ● Support ● Products
Non-default qualifiers.
                 Your custom annotations...
  CDI anno                 @Qualifier
                           @Retention(RUNTIME)
  JavaSE annos             @Target({TYPE, METHOD, FIELD, PARAMETER})
                           public @interface Preferred {}



                 ...links a declared injection point...
                           ...
Your anno                  @Inject @Preferred PaymentService ps;
                           ...


                  ...to a qualified bean
                         @Preferred
                         public class CreditCardPaymentService implements PaymentService {
                           public void process(Payment payment) { ... }
                         }

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

 public PaymentAction {
     @Inject @Preferred PaymentService userPaymentService;
     ...
 }




 public AnyClass {

     @Inject
     User user;

      @Produces @Preferred
      public PaymentService getUserPaymentService() {
         return user.getPaymentServices().get(0);
     }
 }




          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                              JEE defined
✔   @ApplicationScoped
✔   @ConversationScoped                         Defined by you




           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})
CDI anno          @Retention(RUNTIME)
                  public @interface MySecurity {}




                 public class ShoppingCart {
Your anno          @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 @Updated Event<Document> documentEvent;
 ...
 document.setLastModified(new Date());
 documentEvent.fire(document);
                                                    Optional qualifier
Become observer....

 public void handleDocs(@Observes @Updated Document document) { ... }




Conditional observations...

 public void handleDocs(@Observes(during = AFTER_SUCCESS) @Updated Document doc) {
  ..
  }



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

   Use

         @BusinessLogic
         public class UserService { ... }




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




               3. Advices




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
      Annotations are adjectives (@Preferred), not nouns (@CreditCardPayment)
      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... IT Operations ● Training ● Support ● Products
          Consulting ● Development ●
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 :-)

    Generate project using Seam Forge or M2Eclipse

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

Viewers also liked

Gwt cdi jud_con_berlin
Gwt cdi jud_con_berlinGwt cdi jud_con_berlin
Gwt cdi jud_con_berlinhbraun
 
креативное мышление
креативное мышлениекреативное мышление
креативное мышлениеJaneKozmina
 
Семинары и тренинги по делопроизводству, документообороту и архиву предприятия
Семинары и тренинги по делопроизводству, документообороту и архиву предприятияСеминары и тренинги по делопроизводству, документообороту и архиву предприятия
Семинары и тренинги по делопроизводству, документообороту и архиву предприятияProfi-Cariera
 
оценка трудозатрат
оценка трудозатратоценка трудозатрат
оценка трудозатратgaperton
 
Cовременные командные принципы
Cовременные командные принципыCовременные командные принципы
Cовременные командные принципыgaperton
 
Презентация семинаров по деловой переписке с клиентами
Презентация семинаров по деловой переписке с клиентамиПрезентация семинаров по деловой переписке с клиентами
Презентация семинаров по деловой переписке с клиентамиProfi-Cariera
 
PMBOK Extension for Software Projects (in Russian)
PMBOK Extension for Software Projects (in Russian)PMBOK Extension for Software Projects (in Russian)
PMBOK Extension for Software Projects (in Russian)IAMCP MENTORING
 
Корпоративное обучение от "Профи-Карьера"
Корпоративное обучение от "Профи-Карьера"Корпоративное обучение от "Профи-Карьера"
Корпоративное обучение от "Профи-Карьера"Profi-Cariera
 
De Rol van de Registrar in het Museum
De Rol van de Registrar in het MuseumDe Rol van de Registrar in het Museum
De Rol van de Registrar in het Museumguestff8cab
 
Профессиональная разработка требований. Карта онлайн курса
Профессиональная разработка требований. Карта онлайн курсаПрофессиональная разработка требований. Карта онлайн курса
Профессиональная разработка требований. Карта онлайн курсаYulia Madorskaya
 
Промышленная разработка ПО. Лекция 3. Особенности работы программиста. Часть...
Промышленная разработка ПО. Лекция 3. Особенности работы программиста.  Часть...Промышленная разработка ПО. Лекция 3. Особенности работы программиста.  Часть...
Промышленная разработка ПО. Лекция 3. Особенности работы программиста. Часть...Mikhail Payson
 
Тимур Лукин - Архитектура и проектирование ПО
Тимур Лукин - Архитектура и проектирование ПОТимур Лукин - Архитектура и проектирование ПО
Тимур Лукин - Архитектура и проектирование ПОYandex
 
Системное мышление
Системное мышлениеСистемное мышление
Системное мышлениеJaneKozmina
 
Плохой против хорошего консультанта
Плохой против хорошего консультантаПлохой против хорошего консультанта
Плохой против хорошего консультантаJaneKozmina
 
Требования к по
Требования к поТребования к по
Требования к поJaneKozmina
 
Нотации оформления требований
Нотации оформления требованийНотации оформления требований
Нотации оформления требованийJaneKozmina
 
Промышленная разработка ПО. Лекция 8. Особенности работы руководителя проекто...
Промышленная разработка ПО. Лекция 8. Особенности работы руководителя проекто...Промышленная разработка ПО. Лекция 8. Особенности работы руководителя проекто...
Промышленная разработка ПО. Лекция 8. Особенности работы руководителя проекто...Mikhail Payson
 
Методологии разработки по
Методологии разработки поМетодологии разработки по
Методологии разработки поJaneKozmina
 
Организация работы с требованиями и документацией в TFS
Организация работы с требованиями и документацией в TFSОрганизация работы с требованиями и документацией в TFS
Организация работы с требованиями и документацией в TFSАлександр Шамрай
 

Viewers also liked (20)

Gwt cdi jud_con_berlin
Gwt cdi jud_con_berlinGwt cdi jud_con_berlin
Gwt cdi jud_con_berlin
 
креативное мышление
креативное мышлениекреативное мышление
креативное мышление
 
Семинары и тренинги по делопроизводству, документообороту и архиву предприятия
Семинары и тренинги по делопроизводству, документообороту и архиву предприятияСеминары и тренинги по делопроизводству, документообороту и архиву предприятия
Семинары и тренинги по делопроизводству, документообороту и архиву предприятия
 
оценка трудозатрат
оценка трудозатратоценка трудозатрат
оценка трудозатрат
 
Cовременные командные принципы
Cовременные командные принципыCовременные командные принципы
Cовременные командные принципы
 
Презентация семинаров по деловой переписке с клиентами
Презентация семинаров по деловой переписке с клиентамиПрезентация семинаров по деловой переписке с клиентами
Презентация семинаров по деловой переписке с клиентами
 
PMBOK Extension for Software Projects (in Russian)
PMBOK Extension for Software Projects (in Russian)PMBOK Extension for Software Projects (in Russian)
PMBOK Extension for Software Projects (in Russian)
 
Корпоративное обучение от "Профи-Карьера"
Корпоративное обучение от "Профи-Карьера"Корпоративное обучение от "Профи-Карьера"
Корпоративное обучение от "Профи-Карьера"
 
De Rol van de Registrar in het Museum
De Rol van de Registrar in het MuseumDe Rol van de Registrar in het Museum
De Rol van de Registrar in het Museum
 
Профессиональная разработка требований. Карта онлайн курса
Профессиональная разработка требований. Карта онлайн курсаПрофессиональная разработка требований. Карта онлайн курса
Профессиональная разработка требований. Карта онлайн курса
 
Промышленная разработка ПО. Лекция 3. Особенности работы программиста. Часть...
Промышленная разработка ПО. Лекция 3. Особенности работы программиста.  Часть...Промышленная разработка ПО. Лекция 3. Особенности работы программиста.  Часть...
Промышленная разработка ПО. Лекция 3. Особенности работы программиста. Часть...
 
Yyyyyy yyyy 1-8
Yyyyyy yyyy 1-8Yyyyyy yyyy 1-8
Yyyyyy yyyy 1-8
 
Тимур Лукин - Архитектура и проектирование ПО
Тимур Лукин - Архитектура и проектирование ПОТимур Лукин - Архитектура и проектирование ПО
Тимур Лукин - Архитектура и проектирование ПО
 
Системное мышление
Системное мышлениеСистемное мышление
Системное мышление
 
Плохой против хорошего консультанта
Плохой против хорошего консультантаПлохой против хорошего консультанта
Плохой против хорошего консультанта
 
Требования к по
Требования к поТребования к по
Требования к по
 
Нотации оформления требований
Нотации оформления требованийНотации оформления требований
Нотации оформления требований
 
Промышленная разработка ПО. Лекция 8. Особенности работы руководителя проекто...
Промышленная разработка ПО. Лекция 8. Особенности работы руководителя проекто...Промышленная разработка ПО. Лекция 8. Особенности работы руководителя проекто...
Промышленная разработка ПО. Лекция 8. Особенности работы руководителя проекто...
 
Методологии разработки по
Методологии разработки поМетодологии разработки по
Методологии разработки по
 
Организация работы с требованиями и документацией в TFS
Организация работы с требованиями и документацией в TFSОрганизация работы с требованиями и документацией в TFS
Организация работы с требованиями и документацией в TFS
 

Similar to CDI and Weld

CDI and Weld
CDI and WeldCDI and Weld
CDI and Weldjensaug
 
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 ApplicationTeamstudio
 
Service Oriented Architecture in Magento 2
Service Oriented Architecture in Magento 2Service Oriented Architecture in Magento 2
Service Oriented Architecture in Magento 2Max Pronko
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with RailsPaul Gallagher
 
Agile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai ShevchenkoAgile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai ShevchenkoMoldova ICT Summit
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)Woonsan Ko
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConos890
 
Simplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data WarehouseSimplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data WarehouseFeatureByte
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rockmartincronje
 
7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script TaskPramod Singla
 
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 Developerscboecking
 
Expert Image Notes
Expert Image NotesExpert Image Notes
Expert Image NotesMary Clemons
 
Domain-Driven Design with SeedStack
Domain-Driven Design with SeedStackDomain-Driven Design with SeedStack
Domain-Driven Design with SeedStackSeedStack
 
Extending CMS Made Simple
Extending CMS Made SimpleExtending CMS Made Simple
Extending CMS Made Simplecmsmssjg
 

Similar to CDI and Weld (20)

CDI and Weld
CDI and WeldCDI and Weld
CDI and Weld
 
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
 
Service Oriented Architecture in Magento 2
Service Oriented Architecture in Magento 2Service Oriented Architecture in Magento 2
Service Oriented Architecture in Magento 2
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
Multi-tenancy with Rails
Multi-tenancy with RailsMulti-tenancy with Rails
Multi-tenancy with Rails
 
Agile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai ShevchenkoAgile methodologies based on BDD and CI by Nikolai Shevchenko
Agile methodologies based on BDD and CI by Nikolai Shevchenko
 
Gui Report Studio in java
Gui Report Studio in javaGui Report Studio in java
Gui Report Studio in java
 
Relevance trilogy may dream be with you! (dec17)
Relevance trilogy  may dream be with you! (dec17)Relevance trilogy  may dream be with you! (dec17)
Relevance trilogy may dream be with you! (dec17)
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 
Simplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data WarehouseSimplify Feature Engineering in Your Data Warehouse
Simplify Feature Engineering in Your Data Warehouse
 
Clean Architecture @ Taxibeat
Clean Architecture @ TaxibeatClean Architecture @ Taxibeat
Clean Architecture @ Taxibeat
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
 
10 ways to make your code rock
10 ways to make your code rock10 ways to make your code rock
10 ways to make your code rock
 
7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task
 
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
 
Expert Image Notes
Expert Image NotesExpert Image Notes
Expert Image Notes
 
Domain-Driven Design with SeedStack
Domain-Driven Design with SeedStackDomain-Driven Design with SeedStack
Domain-Driven Design with SeedStack
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Extending CMS Made Simple
Extending CMS Made SimpleExtending CMS Made Simple
Extending CMS Made Simple
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 

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. «but I've heard.....» CDI WebBeans old name for... new name for... Hibernate JSR-299 standardized implements... Weld part of... JPA inspired... includes... next project... uses... Java EE 6 Seam 2 Seam 3 JSR-330 created by... Spring Core name for... created by... Guice D4J Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 7. next... 2. CDI Features Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 8. 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
  • 9. Injectable bean types. A user-defined class or interface In a JEE module with a /META-INF/beans.xml public class CreditCardPaymentService declare implements PaymentService { ... } use ... ... @Inject or? @Inject CreditCardPaymentService ps; PaymentService ps; ... ... ...«there can be only one»... Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 10. Non-default qualifiers. Your custom annotations... CDI anno @Qualifier @Retention(RUNTIME) JavaSE annos @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface Preferred {} ...links a declared injection point... ... Your anno @Inject @Preferred PaymentService ps; ... ...to a qualified bean @Preferred public class CreditCardPaymentService implements PaymentService { public void process(Payment payment) { ... } } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 11. Producer methods. Run time qualifier public PaymentAction { @Inject @Preferred PaymentService userPaymentService; ... } public AnyClass { @Inject User user; @Produces @Preferred public PaymentService getUserPaymentService() { return user.getPaymentServices().get(0); } } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 12. 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 JEE defined ✔ @ApplicationScoped ✔ @ConversationScoped Defined by you Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 14. Interceptors. business method interception lifecycle callback interception timeout method interception (ejb3) Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 15. Interceptors - 2. Binding @InterceptorBinding @Target({METHOD, TYPE}) CDI anno @Retention(RUNTIME) public @interface MySecurity {} public class ShoppingCart { Your anno @MySecurity public void checkout() { ... } } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 16. 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
  • 17. 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
  • 18. Events. Become observable.... @Inject @Updated Event<Document> documentEvent; ... document.setLastModified(new Date()); documentEvent.fire(document); Optional qualifier Become observer.... public void handleDocs(@Observes @Updated Document document) { ... } Conditional observations... public void handleDocs(@Observes(during = AFTER_SUCCESS) @Updated Document doc) { .. } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 19. Predefine scope and interceptors Stereotypes. Declare Predefined by CDI: @Model EJB @Stateless @Transactional(requiresNew=true) @Named your @Secure @RequestScoped CDI @Stereotype @Documented @Target(TYPE) @Stereotype JSE @Retention(RUNTIME) @Target(TYPE,METHOD,FIELD) public @interface BusinessLogic {} @Retention(RUNTIME) public @interface Model {} Use @BusinessLogic public class UserService { ... } Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 20. next... 3. Advices Consulting ● Development ● IT Operations ● Training ● Support ● Products
  • 21. 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 Annotations are adjectives (@Preferred), not nouns (@CreditCardPayment) 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... IT Operations ● Training ● Support ● Products Consulting ● Development ●
  • 22. 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 :-) Generate project using Seam Forge or M2Eclipse 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
  • 23. End. jens.augustsson@redpill-linpro.com Consulting ● Development ● IT Operations ● Training ● Support ● Products