SlideShare a Scribd company logo
1 of 75
Download to read offline
CDI (JSR-299), Weld and
the future of Seam



Dan Allen
Senior Software Engineer
JBoss by Red Hat
Who am I?

    ●   Author of Seam in Action, Manning 2008
    ●   Seam Community Liaison
    ●   Weld, Seam & Arquillian project member
    ●   JSR-314 (JSF 2) EG representative
    ●   Open Source advocate



                                                                         mojavelinux



2                   CDI (JSR-299), Weld and the future of Seam | Dan Allen
Agenda

    ●   Terminology
    ●   Why JSR-299?
    ●   JSR-299 themes
    ●   Brief tour of programming model
    ●   Weld
    ●   Seam




3                     CDI (JSR-299), Weld and the future of Seam | Dan Allen
Technology terminology

    ●   CDI (JSR-299)
        ●   Contexts & dependency injection for Java EE
    ●   Weld
        ●   JSR-299 Reference Implementation & TCK
        ●   Extended CDI support (Servlets, Java SE)
        ●   CDI enhancements for extension writers
        ●   Maven archetypes for CDI and Java EE
    ●   Seam 3
        ●   Portable extensions for Java EE
        ●   Integrations with non-Java EE technologies

4                      CDI (JSR-299), Weld and the future of Seam | Dan Allen
Stated goal of JSR-299




                Web tier                     Transactional tier
                 (JSF)                            (EJB)

5            CDI (JSR-299), Weld and the future of Seam | Dan Allen
Why reinvest?
                                                              Java EE 5




6
    Seam 2   CDI (JSR-299), Weld and the future of Seam | Dan Allen
What CDI provides

    ●   Services for Java EE components
         ●   Lifecycle management of stateful beans bound to
             well-defined contexts (including conversation context)
         ●   A type-safe approach to dependency injection
         ●   Interaction via an event notification facility
         ●   Reduced coupling between interceptors and beans
         ●   Decorators, which intercept specific bean instances
         ●   Unified EL integration (bean names)
    ●   SPI for developing extensions for the Java EE platform
         ●   Java EE architecture  flexible, portable, extensible

7                        CDI (JSR-299), Weld and the future of Seam | Dan Allen
What CDI provides

    ●   Services for Java EE components
         ●   Lifecycle management of stateful beans bound to
             well-defined contexts (including conversation context)
         ●   A type-safe approach to dependency injection
         ●   Interaction via an event notification facility
         ●   Reduced coupling between interceptors and beans
         ●   Decorators, which intercept specific bean instances
         ●   Unified EL integration (bean names)
    ●   SPI for developing extensions for the Java EE platform
         ●   Java EE architecture  flexible, portable, extensible

8                        CDI (JSR-299), Weld and the future of Seam | Dan Allen
CDI: The big picture

    ●   Fill in
    ●   Catalyze
    ●   Evolve




9                  CDI (JSR-299), Weld and the future of Seam | Dan Allen
Why injection?

     ●   Weakest aspect of Java EE 5
     ●   Fixed set of injectable resources
          ●   @EJB
          ●   @PersistenceContext, @PersistenceUnit
          ●   @Resource (e.g., DataSource, UserTransaction)
     ●   Name-based injection is fragile
          ●   Not “refactor friendly”
          ●   Requires special tooling to validate




10                        CDI (JSR-299), Weld and the future of Seam | Dan Allen
JSR-299 theme



                                                       @Produces @WishList
 Loose coupling...                                     List<Product> getWishList()

                                                                      Event<Order>
               @InterceptorBinding
     @Inject                                           @UserDatabase EntityManager
                   @Observes
      @Qualifier                                             ...with strong typing




11                   CDI (JSR-299), Weld and the future of Seam | Dan Allen
Loose coupling

     ●
         Decouple server and client
          ●   Using well-defined types and “qualifiers”
          ●   Allows server implementation to vary
     ●
         Decouple lifecycle of collaborating components
          ●   Automatic contextual lifecycle management
          ●   Stateful components interact like services
     ●
         Decouple orthogonal concerns (AOP)
          ●   Interceptors & decorators
     ●
         Decouple message producer from consumer
          ●   Events
12                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Strong typing

     ●   Type-based injection
          ●   Eliminate reliance on string-based names
     ●   Compiler can detect typing errors
          ●   No special authoring tools required
          ●   Casting mostly eliminated
     ●   Semantic code errors detected at application startup
          ●   Tooling can detect ambiguous dependencies




13                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Leverage and extend Java’s type system



     @Annotation                                   <TypeParam>



         This information is pretty useful!



                                Type


14            CDI (JSR-299), Weld and the future of Seam | Dan Allen
Who's bean is it anyway?

     ●   Everyone throwing around this term “bean”
          ●   JSF
          ●   EJB
          ●   Seam
          ●   Spring
          ●   Guice
          ●   CDI
     ●   Need a “unified bean definition”




15                     CDI (JSR-299), Weld and the future of Seam | Dan Allen
Managed bean specification

     ●   Common bean definition
     ●   Instances are managed                                             Managed
         by the container                                                   Beans


     ●   Common services
         ●   Interceptors
         ●   Resource injections
         ●   Lifecycle callbacks                         JSF           EJB         CDI   JAX-RS

     ●   Foundation spec


     How managed beans evolved: http://www.infoq.com/news/2009/11/weld10
16                        CDI (JSR-299), Weld and the future of Seam | Dan Allen
CDI bean ingredients

     ●   Auto-discovered
     ●   Set of bean types
     ●   Set of qualifiers
     ●   Scope
     ●   Bean EL name (optional)
     ●   Set of interceptor bindings
     ●   Alternative classification
     ●   Bean implementation class



17                     CDI (JSR-299), Weld and the future of Seam | Dan Allen
Welcome to CDI, managed beans!

 public class Welcome {
    public String buildPhrase(String city) {
       return "Welcome to " + city + "!";
    }
 }




18               CDI (JSR-299), Weld and the future of Seam | Dan Allen
Welcome to CDI, EJB 3.1 session beans!

 @Stateless public class Welcome {
    public String buildPhrase(String city) {
       return "Welcome to " + city + "!";
    }
 }




19               CDI (JSR-299), Weld and the future of Seam | Dan Allen
When is a bean recognized?

     ●   Bean archive (WAR)                        ●   Bean archive (JAR)




                      beans.xml can be empty!




20                   CDI (JSR-299), Weld and the future of Seam | Dan Allen
Injection 101

 public class Greeter {
    @Inject Welcome w;

     public void welcome() {       @Default qualifier implied
                                   @Default qualifier implied
        System.out.println(
           w.buildPhrase("Reston"));
     }
 }




21                 CDI (JSR-299), Weld and the future of Seam | Dan Allen
Where can it be injected?

     ●   Field
     ●   Method parameter
          ●   Constructor*
          ●   Initializer
          ●   Producer
          ●   Observer




22                          CDI (JSR-299), Weld and the future of Seam | Dan Allen
What can be injected?

     Managed bean

     Object returned by producer

     EJB session bean (local or remote)

     Java EE resource (DataSource, JMS destination, etc)

     JTA UserTransaction

     Persistence unit or context

     Security principle

     Bean Validation factory

     Web service reference

     Additional resources introduced through SPI


23                             CDI (JSR-299), Weld and the future of Seam | Dan Allen
The bean vs “the other implementation”

     ●   Multiple implementations of same interface
     ●   One implementation extends another
 public class Welcome {
    public String buildPhrase(String city) {
       return "Welcome to " + city + "!";
    }
 }

 public class TranslatingWelcome extends Welcome {

         @Inject GoogleTranslator translator;

         public String buildPhrase(String city) {
            return translator.translate(
               "Welcome to " + city + "!");
         }
 }
24                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Quiz: Now which implementation gets injected?

 public class Greeter {
    private Welcome welcome;

     @Inject
     void init(Welcome welcome) {
        this.welcome = welcome;
     }

     ...
 }



                             It's ambiguous!




25                CDI (JSR-299), Weld and the future of Seam | Dan Allen
Settling an ambiguous resolution

     ●   Qualifier
     ●   Alternative
     ●   Hide bean types




26                     CDI (JSR-299), Weld and the future of Seam | Dan Allen
qualifier

     n. an annotation used to resolve an API
     implementation variant at an injection point




27        CDI (JSR-299), Weld and the future of Seam | Dan Allen
Defining a qualifier

     ●   A qualifier is an annotation
 @Qualifier
 @Retention(RUNTIME)
 @Target({TYPE, METHOD, FIELD, PARAMETER})
 public @interface Translating {}




28                     CDI (JSR-299), Weld and the future of Seam | Dan Allen
Qualifying an implementation

     ●   Adding a qualifier annotation:
          ●   makes type more specific
          ●   assigns semantic meaning
 @Translating
 public class TranslatingWelcome extends Welcome {

         @Inject GoogleTranslator translator;

         public String buildPhrase(String city) {
            return translator.translate(
               "Welcome to " + city + "!");
         }
 }




29                      CDI (JSR-299), Weld and the future of Seam | Dan Allen
Qualifier as a “binding type”




30            CDI (JSR-299), Weld and the future of Seam | Dan Allen
Using a specific implementation

     ●   Qualified implementation must be requested explicitly
          ●   Akin to the factory method pattern
     ●   Resolves ambiguity at injection point!
 public class Greeter {
    private Welcome welcome;                         No reference to implementation class!
                                                     No reference to implementation class!
         @Inject
         void init(@Translating Welcome welcome) {
            this.welcome = welcome
         }

         public void welcomeVisitors() {
            System.out.println(
               welcome.buildPhrase("Reston"));
         }
 }
31                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Alternative bean

     ●   Swap replacement implementation per deployment
     ●   Replaces bean and its producer methods and fields
     ●   Disabled by default
          ●   Must be activated in /META-INF/beans.xml


 Put simply: an override




32                      CDI (JSR-299), Weld and the future of Seam | Dan Allen
Defining an alternative

 @Alternative
 public class TranslatingWelcome extends Welcome {

     @Inject GoogleTranslator translator;

     public String buildPhrase(String city) {
        return translator.translate(
           "Welcome to " + city + "!");
     }
 }




33                CDI (JSR-299), Weld and the future of Seam | Dan Allen
Substituting the alternative

     ●   Implementation must be activated using beans.xml
 <beans>
   <alternatives>
     <class>com.acme.TranslatingWelcome</class>
   </alternatives>
 </beans>




34                   CDI (JSR-299), Weld and the future of Seam | Dan Allen
Assigning a bean name

 @Named("greeter")
 public class Greeter {
    private Welcome welcome;

     @Inject
     void init(Welcome welcome) {
        this.welcome = welcome;
     }

     public void welcomeVisitors() {
        System.out.println(
           welcome.buildPhrase("Reston"));
     }
 }




35                CDI (JSR-299), Weld and the future of Seam | Dan Allen
Assigning a bean name by convention

 @Named
 public class Greeter {
    private Welcome welcome;                     Bean name is decapitalized
                                                 Bean name is decapitalized
                                                 simple class name
                                                 simple class name
     @Inject
     void init(Welcome welcome) {
        this.welcome = welcome;
     }

     public void welcomeVisitors() {
        System.out.println(
           welcome.buildPhrase("Reston"));
     }
 }




36                CDI (JSR-299), Weld and the future of Seam | Dan Allen
Welcome to CDI, JSF!

     ●   Use the bean directly in the JSF view
 <h:form>
    <h:commandButton value="Welcome visitors"
       action="#{greeter.welcomeVisitors}"/>
 </h:form>




37                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
JSF
     managed                                                  JSP
      beans



       CDI                                             Facelets


38       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Stashing the bean in a context

     ●   Bean saved for the duration of a request
 @RequestScoped
 @Named("greeter")
 public class Greeter {
    private Welcome welcome;
    private String city; // getter and setter hidden

         @Inject
         void init(Welcome welcome) {
            this.welcome = welcome
         }

         public void welcomeVisitors() {
            System.out.println(welcome.buildPhrase(city));
         }
 }


39                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Collapsing layers with state management

     ●   Now it’s possible for bean to hold state
 <h:form>
    <h:inputText value="#{greeter.city}"/>
    <h:commandButton value="Welcome visitors"
       action="#{greeter.welcomeVisitors}"/>
 </h:form>




     ●   Satisfies initial goal of JSR-299
          ●   ...in fact, integrates JSF and any managed bean


40                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Scope types and contexts

     ●   Absence of scope - @Dependent
          ●   Bound to lifecycle of bean holding reference
     ●   Servlet scopes
          ●   @ApplicationScoped
          ●   @RequestScoped
          ●   @SessionScoped
     ●   JSF conversation scope - @ConversationScoped
     ●   Custom scopes
          ●   Define scope type annotation (e.g., @FlashScoped)
          ●   Implement the context API in an extension
41                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Scope transparency

     ●   Scopes not visible to client
          ●   No coupling between scope and use of type
          ●   Scoped beans are proxied for thread safety




42                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Conversation context

     ●   Request <= Conversation << Session


     ●




     ●   Boundaries demarcated by application


     ●   Optimistic transaction
          ●   Conversation-scoped persistence context
          ●   No fear of exceptions on lazy fetch operations

43                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Controlling the conversation

 @ConversationScoped
 public class BookingAgent {

     @Inject @BookingDatabase EntityManager em;
     @Inject Conversation conversation;

     private Hotel selected;
     private Booking booking;

     public void select(Hotel h) {
        selected = em.find(Hotel.class, h.getId());
        conversation.begin();
     }

     ...




44                CDI (JSR-299), Weld and the future of Seam | Dan Allen
Controlling the conversation

     ...

     public boolean confirm() {
        if (!isValid()) {
           return false;
        }

         em.persist(booking);
         conversation.end();
         return true;
     }
 }




45                 CDI (JSR-299), Weld and the future of Seam | Dan Allen
producer method

     n. a method whose return value produces
     an injectable object




46        CDI (JSR-299), Weld and the future of Seam | Dan Allen
Producer method examples

 @Produces @RequestScoped
 public FacesContext getFacesContext() {                                   From non-bean
                                                                           From non-bean
    return FacesContext.getInstance();
 }

 @Produces
 public PaymentProcessor getPaymentProcessor(
       @Synchronous PaymentProcessor sync,
                                               Runtime selection
                                               Runtime selection
       @Asynchronous PaymentProcessor async) {
    return isSynchronous() ? sync : async;
 }

 @Produces @SessionScoped @WishList            Custom setup
                                                Custom setup
 public List<Product> getWishList() {
    return em.createQuery("...").getResultList();
 }




47                CDI (JSR-299), Weld and the future of Seam | Dan Allen
Bridging Java EE resources

     ●   Use producer field to expose Java EE resource
 @Stateless
 public class UserEntityManagerProducer {
    @Produces @UserRepository
    @PersistenceContext(unitName = "userPU")
    EntityManager em;
 }

 @Stateless
 public class PricesTopicProducer {
    @Produces @Prices
    @Resource(name = "java:global/env/jms/Prices")
    Topic pricesTopic;
 }




48                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Injecting resource in type-safe way

     ●   String-based resource names are hidden
 public class UserManager {
    @Inject @UserRepository EntityManager userEm;
    ...
 }

 public class StockDisplay {
    @Inject @Prices Topic pricesTopic;
    ...
 }




49                   CDI (JSR-299), Weld and the future of Seam | Dan Allen
Rethinking interceptors

 @Interceptors(
    SecurityInterceptor.class,
    TransactionInterceptor.class,
    LoggingInterceptor.class
 )
 @Stateful public class BusinessComponent {
    ...
 }




                      Um, what's the point?




50               CDI (JSR-299), Weld and the future of Seam | Dan Allen
Interceptor wiring in JSR-299 (1)

     ●   Define an interceptor binding type
 @InterceptorBinding
 @Retention(RUNTIME)
 @Target({TYPE, METHOD})
 public @interface Secure {}




51                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Interceptor wiring in JSR-299 (2)

     ●   Marking the interceptor implementation
 @Secure
 @Interceptor
 public class SecurityInterceptor {

         @AroundInvoke
         public Object aroundInvoke(InvocationContext ctx)
               throws Exception {
            // ...enforce security...
            ctx.proceed();
         }

 }




52                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Interceptor wiring in JSR-299 (3)

     ●   Applying interceptor with proper semantics
 @Secure
 public class AccountManager {

         public boolean transfer(Account a, Account b) {
            ...
         }

 }




53                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Multiple interceptors

     ●   Application developer only concerned about semantics
 @Transactional
 public class AccountManager {

         @Secure
         public boolean transfer(Account a, Account b) {
            ...
         }

 }




54                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Enabling and ordering interceptors

     ●   Bean archive has no enabled interceptors by default
     ●   Interceptors activated in beans.xml of bean archive
          ●   Referenced by binding type
          ●   Ordering is per-module
          ●   Declared in module in which the interceptor is used
 <beans>
    <interceptors>
         <class>com.acme.SecurityInterceptor</class>
         <class>com.acme.TransactionInterceptor</class>
    </interceptors>
 </beans>
                                                     Interceptors applied in order listed
                                                     Interceptors applied in order listed



55                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Composite interceptor bindings

     ●   Interceptor binding types can be meta-annotations
 public
 @Secure
 @Transactional
 @InterceptorBinding            Order does not matter
                                 Order does not matter
 @Retention(RUNTIME)
 @Target(TYPE)
 @interface BusinessOperation {}




56                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Multiple interceptors (but you won’t know it)

     ●   Interceptors inherited from composite binding types
 public
 @BusinessOperation
 class AccountManager {

         public boolean transfer(Account a, Account b) {
            ...
         }

 }




57                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Wrap up annotations using stereotypes

     ●   Common architectural patterns – recurring roles
     ●   A stereotype packages:
          ●   A default scope
          ●   A set of interceptor bindings
          ●   The ability to that beans are named
          ●   The ability to specify that beans are alternatives




58                        CDI (JSR-299), Weld and the future of Seam | Dan Allen
Annotation jam!

     ●   Without stereotypes, annotations pile up
 public
 @Secure
 @Transactional
 @RequestScoped
 @Named
 class AccountManager {

         public boolean transfer(Account a, Account b) {
            ...
         }

 }




59                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Defining a stereotype

     ●   Stereotypes are annotations that group annotations
 public
 @Secure
 @Transactional
 @RequestScoped
 @Named
 @Stereotype
 @Retention(RUNTIME)
 @Target(TYPE)
 @interface BusinessComponent {}




60                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Using a stereotype

     ●   Stereotypes give a clear picture, keep things simple
 public
 @BusinessComponent
 class AccountManager {

         public boolean transfer(Account a, Account b) {
            ...
         }

 }




61                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Events

     ●   Completely decouple action and reactions
     ●   Selectors tune which event notifications are received
     ●   Can be observed:
          ●   immediately,
          ●   after transaction completion or
          ●   asynchronously (via extension)




62                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Firing an event                                                            Event instance with
                                                                           Event instance with
                                                                           type-safe payload
                                                                           type-safe payload
 public class GroundController {
    @Inject @Landing Event<Flight> flightLanding;

     public void clearForLanding(String flightNum) {
        flightLanding.fire(new Flight(flightNum));
     }
 }




63                CDI (JSR-299), Weld and the future of Seam | Dan Allen
An event observer
                                                                  Takes event API type with
                                                                  Takes event API type with
 public class GateServices {                                      additional binding type
                                                                  additional binding type
    public void onIncomingFlight(
          @Observes @Landing Flight flight,
          Greeter greeter,
          CateringService cateringService) {
       Gate gate = ...;
       flight.setGate(gate);
       cateringService.dispatch(gate);
       greeter.welcomeVisitors();
    }
 }
                                                              Additional parameters are
                                                               Additional parameters are
                                                              injected by the container
                                                               injected by the container




64               CDI (JSR-299), Weld and the future of Seam | Dan Allen
Weld: JSR-299 Reference Implementation

     ●   Developed under Seam project umbrella
     ●   Version 1.0.1 available
     ●   Bundled in JBoss AS 6 & GlassFish V3
     ●   Support for Tomcat, Jetty & Java SE
     ●   CDI enhancements & utilities for extension writers
     ●   Maven archetypes for CDI & Java EE




65                    CDI (JSR-299), Weld and the future of Seam | Dan Allen
Seam’s mission statement




       To provide a fully integrated development
     platform for building rich Internet applications
         based upon the Java EE environment.




66             CDI (JSR-299), Weld and the future of Seam | Dan Allen
Seam 3: Key themes

     ●   Portability
          ●   Portable extensions run on any CDI implementation
     ●   Modularity (i.e., Seam à la carte)
          ●   Module per integration
          ●   Individual module leads
          ●   Independent release cycles
     ●   “Stack” releases
     ●   Strong tooling
          ●   Java compiler
          ●   JBoss Tools
67                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
Seam's new modular ecosystem




68          CDI (JSR-299), Weld and the future of Seam | Dan Allen
What's on the menu so far?

     ●   Drools                                        ●   JavaScript Remoting
     ●   JMS                                           ●   Security
     ●   Faces                                         ●   Servlet
     ●   International                                 ●   Wicket
     ●   Persistence                                   ●   XML configuration


                                                           ...and more
                                                               http://sfwk.org/Seam3



69                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
XML-based configuration

 <beans ...
    xmlns:app="java:urn:com.acme">
    <app:TranslatingWelcome>
       <app:Translating/>
       <app:defaultLocale>en-US</app:defaultLocale>
    </app:TranslatingWelcome>
 </beans>



     ●   Define, specialize or override beans
     ●   Add annotations (qualifiers, interceptor bindings, ...)
     ●   Assign initial property values



70                     CDI (JSR-299), Weld and the future of Seam | Dan Allen
End-to-end testing for Java EE

     ●   SeamTest replacement
     ●   ShrinkWrap
          ●   Fluent API for creating Java archives
 JavaArchive archive =
    ShrinkWrap.create("archive.jar", JavaArchive.class)
       .addClasses(MyClass.class, MyOtherClass.class)
       .addResource("mystuff.properties");
     ●   Arquillian
          ●   Integration test harness
          ●   Pluggable container support (embedded or remote)
          ●   Supports injection into test class
          ●   Tests can be run from IDE or build script
71                        CDI (JSR-299), Weld and the future of Seam | Dan Allen
72   CDI (JSR-299), Weld and the future of Seam | Dan Allen
Summary

     ●   JSR-299 provides a set of services for Java EE
          ●   Bridges JSF and EJB
          ●   Offers loose coupling with strong typing
          ●   Catalyzed managed bean & interceptor specifications
     ●   Extensive SPI for third-party integration with Java EE
     ●   Weld: JSR-299 Reference Implementation
     ●   Seam 3: Portable extensions for Java EE




73                       CDI (JSR-299), Weld and the future of Seam | Dan Allen
How do I get started with CDI or Java EE 6?

     ●   Seam 3 project
         http://seamframework.org/Seam3
     ●   Weld Maven archetypes for CDI and Java EE
         http://tinyurl.com/goweld
     ●   Weld reference guide
         http://tinyurl.com/weld-reference-101
     ●   CDI JavaDoc
         http://docs.jboss.org/cdi/api/latest/
     ●   Any Java EE 6 container!



74                     CDI (JSR-299), Weld and the future of Seam | Dan Allen
Q&A


Dan Allen
Senior Software Engineer
JBoss, by Red Hat

http://in.relation.to
http://seamframework.org/Seam3

More Related Content

Viewers also liked

To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionAntonio Goncalves
 
Special casting Techniques
Special casting TechniquesSpecial casting Techniques
Special casting TechniquesM Siva Kumar
 
Plastic forming techniques
Plastic forming techniquesPlastic forming techniques
Plastic forming techniquesM Siva Kumar
 

Viewers also liked (8)

To inject or not to inject: CDI is the question
To inject or not to inject: CDI is the questionTo inject or not to inject: CDI is the question
To inject or not to inject: CDI is the question
 
CDI: How do I ?
CDI: How do I ?CDI: How do I ?
CDI: How do I ?
 
Extrusion Process
Extrusion ProcessExtrusion Process
Extrusion Process
 
Rolling Process
Rolling ProcessRolling Process
Rolling Process
 
Special casting Techniques
Special casting TechniquesSpecial casting Techniques
Special casting Techniques
 
Gas Welding
Gas WeldingGas Welding
Gas Welding
 
Plastic forming techniques
Plastic forming techniquesPlastic forming techniques
Plastic forming techniques
 
Welding defects
Welding defectsWelding defects
Welding defects
 

Similar to CDI, Weld and the future of Seam

Gustavo Garnica: Evolución de la Plataforma Java y lo que Significa para Ti
Gustavo Garnica: Evolución de la Plataforma Java y lo que Significa para TiGustavo Garnica: Evolución de la Plataforma Java y lo que Significa para Ti
Gustavo Garnica: Evolución de la Plataforma Java y lo que Significa para TiSoftware Guru
 
DDD&Scalaで作られたプロダクトはその後どうなったか?(Current state of products made with DDD & Scala)
DDD&Scalaで作られたプロダクトはその後どうなったか?(Current state of products made with DDD & Scala)DDD&Scalaで作られたプロダクトはその後どうなったか?(Current state of products made with DDD & Scala)
DDD&Scalaで作られたプロダクトはその後どうなったか?(Current state of products made with DDD & Scala)MicroAd, Inc.(Engineer)
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI InteropRay Ploski
 
Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011Arun Gupta
 
Groovy In the Cloud
Groovy In the CloudGroovy In the Cloud
Groovy In the CloudJim Driscoll
 
OTN Developer Days - Java EE 6
OTN Developer Days - Java EE 6OTN Developer Days - Java EE 6
OTN Developer Days - Java EE 6glassfish
 
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)ZFConf Conference
 
Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»e-Legion
 
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Vladimir Bacvanski, PhD
 
Haj 4344-java se 9 and the application server-1
Haj 4344-java se 9 and the application server-1Haj 4344-java se 9 and the application server-1
Haj 4344-java se 9 and the application server-1Kevin Sutter
 
Zend Framework 2 quick start
Zend Framework 2 quick startZend Framework 2 quick start
Zend Framework 2 quick startEnrico Zimuel
 
Java2 MicroEdition-J2ME
Java2 MicroEdition-J2MEJava2 MicroEdition-J2ME
Java2 MicroEdition-J2MERohan Chandane
 
CDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily JiangCDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily Jiangmfrancis
 
Illia shestakov - The Future of Java JDK #9
Illia shestakov - The Future of Java JDK #9Illia shestakov - The Future of Java JDK #9
Illia shestakov - The Future of Java JDK #9Anna Shymchenko
 
MongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataChris Richardson
 
GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012Arun Gupta
 
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...Databricks
 
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon Web Services Korea
 

Similar to CDI, Weld and the future of Seam (20)

Gustavo Garnica: Evolución de la Plataforma Java y lo que Significa para Ti
Gustavo Garnica: Evolución de la Plataforma Java y lo que Significa para TiGustavo Garnica: Evolución de la Plataforma Java y lo que Significa para Ti
Gustavo Garnica: Evolución de la Plataforma Java y lo que Significa para Ti
 
DDD&Scalaで作られたプロダクトはその後どうなったか?(Current state of products made with DDD & Scala)
DDD&Scalaで作られたプロダクトはその後どうなったか?(Current state of products made with DDD & Scala)DDD&Scalaで作られたプロダクトはその後どうなったか?(Current state of products made with DDD & Scala)
DDD&Scalaで作られたプロダクトはその後どうなったか?(Current state of products made with DDD & Scala)
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI Interop
 
Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011Java EE 6 workshop at Dallas Tech Fest 2011
Java EE 6 workshop at Dallas Tech Fest 2011
 
Groovy In the Cloud
Groovy In the CloudGroovy In the Cloud
Groovy In the Cloud
 
Grails 101
Grails 101Grails 101
Grails 101
 
OTN Developer Days - Java EE 6
OTN Developer Days - Java EE 6OTN Developer Days - Java EE 6
OTN Developer Days - Java EE 6
 
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
ZFConf 2012: Zend Framework 2, a quick start (Enrico Zimuel)
 
Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»Rafael Bagmanov «Scala in a wild enterprise»
Rafael Bagmanov «Scala in a wild enterprise»
 
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
Revolutionizing the Data Abstraction Layer with IBM Optim pureQuery and DB2
 
Haj 4344-java se 9 and the application server-1
Haj 4344-java se 9 and the application server-1Haj 4344-java se 9 and the application server-1
Haj 4344-java se 9 and the application server-1
 
Zend Framework 2 quick start
Zend Framework 2 quick startZend Framework 2 quick start
Zend Framework 2 quick start
 
Java2 MicroEdition-J2ME
Java2 MicroEdition-J2MEJava2 MicroEdition-J2ME
Java2 MicroEdition-J2ME
 
CDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily JiangCDI Integration in OSGi - Emily Jiang
CDI Integration in OSGi - Emily Jiang
 
Illia shestakov - The Future of Java JDK #9
Illia shestakov - The Future of Java JDK #9Illia shestakov - The Future of Java JDK #9
Illia shestakov - The Future of Java JDK #9
 
MongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring DataMongoDB for Java Developers with Spring Data
MongoDB for Java Developers with Spring Data
 
GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012
 
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
Spark SQL Adaptive Execution Unleashes The Power of Cluster in Large Scale wi...
 
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
Amazon DocumentDB vs MongoDB 의 내부 아키텍쳐 와 장단점 비교
 
Icsm11a.ppt
Icsm11a.pptIcsm11a.ppt
Icsm11a.ppt
 

Recently uploaded

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 

Recently uploaded (20)

Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 

CDI, Weld and the future of Seam

  • 1. CDI (JSR-299), Weld and the future of Seam Dan Allen Senior Software Engineer JBoss by Red Hat
  • 2. Who am I? ● Author of Seam in Action, Manning 2008 ● Seam Community Liaison ● Weld, Seam & Arquillian project member ● JSR-314 (JSF 2) EG representative ● Open Source advocate mojavelinux 2 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 3. Agenda ● Terminology ● Why JSR-299? ● JSR-299 themes ● Brief tour of programming model ● Weld ● Seam 3 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 4. Technology terminology ● CDI (JSR-299) ● Contexts & dependency injection for Java EE ● Weld ● JSR-299 Reference Implementation & TCK ● Extended CDI support (Servlets, Java SE) ● CDI enhancements for extension writers ● Maven archetypes for CDI and Java EE ● Seam 3 ● Portable extensions for Java EE ● Integrations with non-Java EE technologies 4 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 5. Stated goal of JSR-299 Web tier Transactional tier (JSF) (EJB) 5 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 6. Why reinvest? Java EE 5 6 Seam 2 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 7. What CDI provides ● Services for Java EE components ● Lifecycle management of stateful beans bound to well-defined contexts (including conversation context) ● A type-safe approach to dependency injection ● Interaction via an event notification facility ● Reduced coupling between interceptors and beans ● Decorators, which intercept specific bean instances ● Unified EL integration (bean names) ● SPI for developing extensions for the Java EE platform ● Java EE architecture  flexible, portable, extensible 7 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 8. What CDI provides ● Services for Java EE components ● Lifecycle management of stateful beans bound to well-defined contexts (including conversation context) ● A type-safe approach to dependency injection ● Interaction via an event notification facility ● Reduced coupling between interceptors and beans ● Decorators, which intercept specific bean instances ● Unified EL integration (bean names) ● SPI for developing extensions for the Java EE platform ● Java EE architecture  flexible, portable, extensible 8 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 9. CDI: The big picture ● Fill in ● Catalyze ● Evolve 9 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 10. Why injection? ● Weakest aspect of Java EE 5 ● Fixed set of injectable resources ● @EJB ● @PersistenceContext, @PersistenceUnit ● @Resource (e.g., DataSource, UserTransaction) ● Name-based injection is fragile ● Not “refactor friendly” ● Requires special tooling to validate 10 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 11. JSR-299 theme @Produces @WishList Loose coupling... List<Product> getWishList() Event<Order> @InterceptorBinding @Inject @UserDatabase EntityManager @Observes @Qualifier ...with strong typing 11 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 12. Loose coupling ● Decouple server and client ● Using well-defined types and “qualifiers” ● Allows server implementation to vary ● Decouple lifecycle of collaborating components ● Automatic contextual lifecycle management ● Stateful components interact like services ● Decouple orthogonal concerns (AOP) ● Interceptors & decorators ● Decouple message producer from consumer ● Events 12 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 13. Strong typing ● Type-based injection ● Eliminate reliance on string-based names ● Compiler can detect typing errors ● No special authoring tools required ● Casting mostly eliminated ● Semantic code errors detected at application startup ● Tooling can detect ambiguous dependencies 13 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 14. Leverage and extend Java’s type system @Annotation <TypeParam> This information is pretty useful! Type 14 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 15. Who's bean is it anyway? ● Everyone throwing around this term “bean” ● JSF ● EJB ● Seam ● Spring ● Guice ● CDI ● Need a “unified bean definition” 15 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 16. Managed bean specification ● Common bean definition ● Instances are managed Managed by the container Beans ● Common services ● Interceptors ● Resource injections ● Lifecycle callbacks JSF EJB CDI JAX-RS ● Foundation spec How managed beans evolved: http://www.infoq.com/news/2009/11/weld10 16 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 17. CDI bean ingredients ● Auto-discovered ● Set of bean types ● Set of qualifiers ● Scope ● Bean EL name (optional) ● Set of interceptor bindings ● Alternative classification ● Bean implementation class 17 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 18. Welcome to CDI, managed beans! public class Welcome { public String buildPhrase(String city) { return "Welcome to " + city + "!"; } } 18 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 19. Welcome to CDI, EJB 3.1 session beans! @Stateless public class Welcome { public String buildPhrase(String city) { return "Welcome to " + city + "!"; } } 19 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 20. When is a bean recognized? ● Bean archive (WAR) ● Bean archive (JAR) beans.xml can be empty! 20 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 21. Injection 101 public class Greeter { @Inject Welcome w; public void welcome() { @Default qualifier implied @Default qualifier implied System.out.println( w.buildPhrase("Reston")); } } 21 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 22. Where can it be injected? ● Field ● Method parameter ● Constructor* ● Initializer ● Producer ● Observer 22 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 23. What can be injected? Managed bean Object returned by producer EJB session bean (local or remote) Java EE resource (DataSource, JMS destination, etc) JTA UserTransaction Persistence unit or context Security principle Bean Validation factory Web service reference Additional resources introduced through SPI 23 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 24. The bean vs “the other implementation” ● Multiple implementations of same interface ● One implementation extends another public class Welcome { public String buildPhrase(String city) { return "Welcome to " + city + "!"; } } public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate( "Welcome to " + city + "!"); } } 24 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 25. Quiz: Now which implementation gets injected? public class Greeter { private Welcome welcome; @Inject void init(Welcome welcome) { this.welcome = welcome; } ... } It's ambiguous! 25 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 26. Settling an ambiguous resolution ● Qualifier ● Alternative ● Hide bean types 26 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 27. qualifier n. an annotation used to resolve an API implementation variant at an injection point 27 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 28. Defining a qualifier ● A qualifier is an annotation @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER}) public @interface Translating {} 28 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 29. Qualifying an implementation ● Adding a qualifier annotation: ● makes type more specific ● assigns semantic meaning @Translating public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate( "Welcome to " + city + "!"); } } 29 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 30. Qualifier as a “binding type” 30 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 31. Using a specific implementation ● Qualified implementation must be requested explicitly ● Akin to the factory method pattern ● Resolves ambiguity at injection point! public class Greeter { private Welcome welcome; No reference to implementation class! No reference to implementation class! @Inject void init(@Translating Welcome welcome) { this.welcome = welcome } public void welcomeVisitors() { System.out.println( welcome.buildPhrase("Reston")); } } 31 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 32. Alternative bean ● Swap replacement implementation per deployment ● Replaces bean and its producer methods and fields ● Disabled by default ● Must be activated in /META-INF/beans.xml Put simply: an override 32 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 33. Defining an alternative @Alternative public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate( "Welcome to " + city + "!"); } } 33 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 34. Substituting the alternative ● Implementation must be activated using beans.xml <beans> <alternatives> <class>com.acme.TranslatingWelcome</class> </alternatives> </beans> 34 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 35. Assigning a bean name @Named("greeter") public class Greeter { private Welcome welcome; @Inject void init(Welcome welcome) { this.welcome = welcome; } public void welcomeVisitors() { System.out.println( welcome.buildPhrase("Reston")); } } 35 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 36. Assigning a bean name by convention @Named public class Greeter { private Welcome welcome; Bean name is decapitalized Bean name is decapitalized simple class name simple class name @Inject void init(Welcome welcome) { this.welcome = welcome; } public void welcomeVisitors() { System.out.println( welcome.buildPhrase("Reston")); } } 36 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 37. Welcome to CDI, JSF! ● Use the bean directly in the JSF view <h:form> <h:commandButton value="Welcome visitors" action="#{greeter.welcomeVisitors}"/> </h:form> 37 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 38. JSF managed JSP beans CDI Facelets 38 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 39. Stashing the bean in a context ● Bean saved for the duration of a request @RequestScoped @Named("greeter") public class Greeter { private Welcome welcome; private String city; // getter and setter hidden @Inject void init(Welcome welcome) { this.welcome = welcome } public void welcomeVisitors() { System.out.println(welcome.buildPhrase(city)); } } 39 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 40. Collapsing layers with state management ● Now it’s possible for bean to hold state <h:form> <h:inputText value="#{greeter.city}"/> <h:commandButton value="Welcome visitors" action="#{greeter.welcomeVisitors}"/> </h:form> ● Satisfies initial goal of JSR-299 ● ...in fact, integrates JSF and any managed bean 40 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 41. Scope types and contexts ● Absence of scope - @Dependent ● Bound to lifecycle of bean holding reference ● Servlet scopes ● @ApplicationScoped ● @RequestScoped ● @SessionScoped ● JSF conversation scope - @ConversationScoped ● Custom scopes ● Define scope type annotation (e.g., @FlashScoped) ● Implement the context API in an extension 41 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 42. Scope transparency ● Scopes not visible to client ● No coupling between scope and use of type ● Scoped beans are proxied for thread safety 42 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 43. Conversation context ● Request <= Conversation << Session ● ● Boundaries demarcated by application ● Optimistic transaction ● Conversation-scoped persistence context ● No fear of exceptions on lazy fetch operations 43 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 44. Controlling the conversation @ConversationScoped public class BookingAgent { @Inject @BookingDatabase EntityManager em; @Inject Conversation conversation; private Hotel selected; private Booking booking; public void select(Hotel h) { selected = em.find(Hotel.class, h.getId()); conversation.begin(); } ... 44 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 45. Controlling the conversation ... public boolean confirm() { if (!isValid()) { return false; } em.persist(booking); conversation.end(); return true; } } 45 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 46. producer method n. a method whose return value produces an injectable object 46 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 47. Producer method examples @Produces @RequestScoped public FacesContext getFacesContext() { From non-bean From non-bean return FacesContext.getInstance(); } @Produces public PaymentProcessor getPaymentProcessor( @Synchronous PaymentProcessor sync, Runtime selection Runtime selection @Asynchronous PaymentProcessor async) { return isSynchronous() ? sync : async; } @Produces @SessionScoped @WishList Custom setup Custom setup public List<Product> getWishList() { return em.createQuery("...").getResultList(); } 47 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 48. Bridging Java EE resources ● Use producer field to expose Java EE resource @Stateless public class UserEntityManagerProducer { @Produces @UserRepository @PersistenceContext(unitName = "userPU") EntityManager em; } @Stateless public class PricesTopicProducer { @Produces @Prices @Resource(name = "java:global/env/jms/Prices") Topic pricesTopic; } 48 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 49. Injecting resource in type-safe way ● String-based resource names are hidden public class UserManager { @Inject @UserRepository EntityManager userEm; ... } public class StockDisplay { @Inject @Prices Topic pricesTopic; ... } 49 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 50. Rethinking interceptors @Interceptors( SecurityInterceptor.class, TransactionInterceptor.class, LoggingInterceptor.class ) @Stateful public class BusinessComponent { ... } Um, what's the point? 50 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 51. Interceptor wiring in JSR-299 (1) ● Define an interceptor binding type @InterceptorBinding @Retention(RUNTIME) @Target({TYPE, METHOD}) public @interface Secure {} 51 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 52. Interceptor wiring in JSR-299 (2) ● Marking the interceptor implementation @Secure @Interceptor public class SecurityInterceptor { @AroundInvoke public Object aroundInvoke(InvocationContext ctx) throws Exception { // ...enforce security... ctx.proceed(); } } 52 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 53. Interceptor wiring in JSR-299 (3) ● Applying interceptor with proper semantics @Secure public class AccountManager { public boolean transfer(Account a, Account b) { ... } } 53 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 54. Multiple interceptors ● Application developer only concerned about semantics @Transactional public class AccountManager { @Secure public boolean transfer(Account a, Account b) { ... } } 54 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 55. Enabling and ordering interceptors ● Bean archive has no enabled interceptors by default ● Interceptors activated in beans.xml of bean archive ● Referenced by binding type ● Ordering is per-module ● Declared in module in which the interceptor is used <beans> <interceptors> <class>com.acme.SecurityInterceptor</class> <class>com.acme.TransactionInterceptor</class> </interceptors> </beans> Interceptors applied in order listed Interceptors applied in order listed 55 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 56. Composite interceptor bindings ● Interceptor binding types can be meta-annotations public @Secure @Transactional @InterceptorBinding Order does not matter Order does not matter @Retention(RUNTIME) @Target(TYPE) @interface BusinessOperation {} 56 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 57. Multiple interceptors (but you won’t know it) ● Interceptors inherited from composite binding types public @BusinessOperation class AccountManager { public boolean transfer(Account a, Account b) { ... } } 57 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 58. Wrap up annotations using stereotypes ● Common architectural patterns – recurring roles ● A stereotype packages: ● A default scope ● A set of interceptor bindings ● The ability to that beans are named ● The ability to specify that beans are alternatives 58 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 59. Annotation jam! ● Without stereotypes, annotations pile up public @Secure @Transactional @RequestScoped @Named class AccountManager { public boolean transfer(Account a, Account b) { ... } } 59 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 60. Defining a stereotype ● Stereotypes are annotations that group annotations public @Secure @Transactional @RequestScoped @Named @Stereotype @Retention(RUNTIME) @Target(TYPE) @interface BusinessComponent {} 60 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 61. Using a stereotype ● Stereotypes give a clear picture, keep things simple public @BusinessComponent class AccountManager { public boolean transfer(Account a, Account b) { ... } } 61 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 62. Events ● Completely decouple action and reactions ● Selectors tune which event notifications are received ● Can be observed: ● immediately, ● after transaction completion or ● asynchronously (via extension) 62 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 63. Firing an event Event instance with Event instance with type-safe payload type-safe payload public class GroundController { @Inject @Landing Event<Flight> flightLanding; public void clearForLanding(String flightNum) { flightLanding.fire(new Flight(flightNum)); } } 63 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 64. An event observer Takes event API type with Takes event API type with public class GateServices { additional binding type additional binding type public void onIncomingFlight( @Observes @Landing Flight flight, Greeter greeter, CateringService cateringService) { Gate gate = ...; flight.setGate(gate); cateringService.dispatch(gate); greeter.welcomeVisitors(); } } Additional parameters are Additional parameters are injected by the container injected by the container 64 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 65. Weld: JSR-299 Reference Implementation ● Developed under Seam project umbrella ● Version 1.0.1 available ● Bundled in JBoss AS 6 & GlassFish V3 ● Support for Tomcat, Jetty & Java SE ● CDI enhancements & utilities for extension writers ● Maven archetypes for CDI & Java EE 65 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 66. Seam’s mission statement To provide a fully integrated development platform for building rich Internet applications based upon the Java EE environment. 66 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 67. Seam 3: Key themes ● Portability ● Portable extensions run on any CDI implementation ● Modularity (i.e., Seam à la carte) ● Module per integration ● Individual module leads ● Independent release cycles ● “Stack” releases ● Strong tooling ● Java compiler ● JBoss Tools 67 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 68. Seam's new modular ecosystem 68 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 69. What's on the menu so far? ● Drools ● JavaScript Remoting ● JMS ● Security ● Faces ● Servlet ● International ● Wicket ● Persistence ● XML configuration ...and more  http://sfwk.org/Seam3 69 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 70. XML-based configuration <beans ... xmlns:app="java:urn:com.acme"> <app:TranslatingWelcome> <app:Translating/> <app:defaultLocale>en-US</app:defaultLocale> </app:TranslatingWelcome> </beans> ● Define, specialize or override beans ● Add annotations (qualifiers, interceptor bindings, ...) ● Assign initial property values 70 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 71. End-to-end testing for Java EE ● SeamTest replacement ● ShrinkWrap ● Fluent API for creating Java archives JavaArchive archive = ShrinkWrap.create("archive.jar", JavaArchive.class) .addClasses(MyClass.class, MyOtherClass.class) .addResource("mystuff.properties"); ● Arquillian ● Integration test harness ● Pluggable container support (embedded or remote) ● Supports injection into test class ● Tests can be run from IDE or build script 71 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 72. 72 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 73. Summary ● JSR-299 provides a set of services for Java EE ● Bridges JSF and EJB ● Offers loose coupling with strong typing ● Catalyzed managed bean & interceptor specifications ● Extensive SPI for third-party integration with Java EE ● Weld: JSR-299 Reference Implementation ● Seam 3: Portable extensions for Java EE 73 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 74. How do I get started with CDI or Java EE 6? ● Seam 3 project http://seamframework.org/Seam3 ● Weld Maven archetypes for CDI and Java EE http://tinyurl.com/goweld ● Weld reference guide http://tinyurl.com/weld-reference-101 ● CDI JavaDoc http://docs.jboss.org/cdi/api/latest/ ● Any Java EE 6 container! 74 CDI (JSR-299), Weld and the future of Seam | Dan Allen
  • 75. Q&A Dan Allen Senior Software Engineer JBoss, by Red Hat http://in.relation.to http://seamframework.org/Seam3