SlideShare a Scribd company logo
<Insert Picture Here>




Contexts And Dependency Injection In The Java EE 6 Ecosystem
Arun Gupta, Java EE & GlassFish Guy
blogs.sun.com/arungupta, @arungupta
The following is intended to outline our general product
direction. It is intended for information purposes only,
and may not be incorporated into any contract. It is not a
commitment to deliver any material, code, or functionality,
and should not be relied upon in making purchasing
decisions.
The development, release, and timing of any features or
functionality described for Oracle’s products remains at the
sole discretion of Oracle.


                                                               2
How we got here ?


• Java EE 5 had resource injection
  – @EJB, @PersistenceUnit, @Resource
• Motivated by Seam, Guice, and Spring
  – More typesafe than Seam
  – More stateful and less XML-centric than Spring
  – More web and enterprise-capable than Guice
• Adapts JSR 330 for Java EE environments
  – @Inject, @Qualifier, @ScopeType



                                                     3
CDI Key Concepts

• Type-safe approach to Dependency Injection
• Strong typing, Loose coupling
  – Events, Interceptors, Decorators
• Context & Scope management
• Works with Java EE modular and component architecture
  – Integration with Unified Expression Language (UEL)
• Portable extensions
• Bridge EJB (transactional tier) and JSF (presentation tier) in
  the platform

                                                                   4
What is a CDI managed bean ?


• “Beans”
  – All managed beans by other Java EE specifications
    • Except JPA
  – Meets the following conditions
    • Non-static inner class
    • Concrete class or decorated with @Decorator
    • Constructor with no parameters or a constructor annotated with @Inject
• “Contextual instances” - Instances of “beans” that belong to
  contexts

                                                                               5
How to configure ?
There is none!


• Discovers bean in all modules in which CDI is enabled
• “beans.xml”
  – WEB-INF of WAR
  – META-INF of JAR
  – META-INF of directory in the classpath
• Can enable groups of bean selectively via a descriptor




                                                           6
Injection Points


• Field, Method, Constructor
• 0 or more qualifiers
                                   Which one ?
• Type                              (Qualifier)




              @Inject @LoggedIn User user
  Request                                         What ?
  Injection                                       (Type)

                                                           7
Basic – Sample Code

public interface Greeting {
    public String sayHello(String name);           Default “dependent”
                                                          scope
}

public class HelloGreeting implements Greeting {
    public String sayHello(String name) {
        return “Hello “ + name;
    }
}

@Stateless
public class GreetingService {
    @Inject Greeting greeting;

    public String sayHello(String name) {           No String identifiers,
        return greeting.sayHello(name);                   All Java
    }
}



                                                                             8
Qualifier


• Annotation to uniquely identify a bean to be injected
• Built-in qualifiers
  – @Named required for usage in EL
  – @Default qualifier on all beans marked with/without @Named
  – @Any implicit qualifier for all beans (except @New)
  – @New




                                                            9
Qualifier – Sample Code
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Texan {
}


@Texan
public class HowdyGreeting implements Greeting {
    public String sayHello(String name) {
        return “Howdy “ + name;
    }
}

@Stateless
public class GreetingService {
    @Inject @Texan Greeting greeting;

    public String sayHello(String name) {
        return greeting.sayHello(name);
    }
}




                                                   10
Field and Method Injection


public class CheckoutHandler {

    @Inject @LoggedIn User user;

    @Inject PaymentProcessor processor;

    @Inject
    void setShoppingCart(@Default Cart cart) {
       …
    }

}


                                                 11
Constructor Injection


 public class CheckoutHandler {

     @Inject
     CheckoutHandler(@LoggedIn User user,
                     PaymentProcessor processor,
                     Cart cart) {
       ...
     }

 }

• Only one constructor can have @Inject
• Makes the bean immutable

                                                   12
Multiple Qualifiers and Qualifiers with Arguments


public class CheckoutHandler {

    @Inject
    CheckoutHandler(@LoggedIn User user,
                    @Reliable
                    @PayBy(CREDIT_CARD)
                    PaymentProcessor processor,
                    @Default Cart cart) {
      ...
    }

}


                                                    13
Typesafe Resolution

• Resolution is performed at system initialization time
• @Qualifier, @Alternative
  – Unsatisfied dependency
    • Create a bean which implements the bean type with all qualifiers
    • Explicitly enable an @Alternative bean using beans.xml
    • Make sure it is in the classpath
  – Ambiguous dependency
    • Introduce a qualifier
    • Disable one of the beans using @Alternative
    • Move one implementation out of classpath


                                                                         14
Client Proxies

• Container indirects all injected references through a proxy
  object unless it is @Dependent
• Proxies may be shared between multiple injection points
@ApplicationScoped                @RequestScoped
public class UserService {        public class User {
                                    private String message;
    @Inject User user;              // getter & setter
                                  }
    public void doSomething() {
      user.setMessage("...");
      // some other stuff
      user.getMessage();
    }
}


                                                                15
Scopes

• Beans can be declared in a scope
  – Everywhere: @ApplicationScoped, @RequestScoped
  – Web app: @SessionScoped (must be serializable)
  – JSF app: @ConversationScoped
    • Transient and long-running
  – Pseudo-scope (default): @Dependent
  – Custom scopes via @Scope
• Runtime makes sure the right bean is created at the right time
• Client do NOT have to be scope-aware


                                                                   16
ConversationScope – Sample Code

• Like session-scope – spans multiple requests to the server
• Unlike – demarcated explicitly by the application, holds state
  with a particular browser tab in a JSF application
 public class ShoppingService {
   @Inject Conversation conv;

     public void startShopping() {
       conv.begin();
     }

     . . .

     public void checkOut() {
       conv.end();
     }
 }


                                                                   17
Custom Scopes – Sample Code


@ScopeType
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface ClusterScoped {}

public @interface TransactionScoped {}


public @interface ThreadScoped {}




                                         18
Producer & Disposer
• Producer
  – Exposes any non-bean class as a bean, e.g. a JPA entity
  – Bridge the gap with Java EE DI
  – Perform custom initialization not possible in a constructor
  – Define multiple beans, with different scopes or initialization, for the
    same implementation class
  – Method or field
  – Runtime polymorphism
• Disposer – cleans up the “produced” object
  – e.g. explicitly closing JDBC connection
  – Defined in the same class as the “producer” method

                                                                              19
Producer – Sample Code

@SessionScoped
public class Preferences implements Serializable {
                                                             How often the method is called,
   private PaymentStrategyType paymentStrategy;
                                                             Lifecycle of the objects returned
    . . .
                                                                  Default is @Dependent
    @Produces @Preferred @SessionScoped
    public PaymentStrategy getPaymentStrategy() {
        switch (paymentStrategy) {
            case CREDIT_CARD: return new CreditCardPaymentStrategy();
            case CHECK: return new CheckPaymentStrategy();
            case PAYPAL: return new PayPalPaymentStrategy();
            default: return null;
        }
    }
}


@Inject @Preferred PaymentStrategy paymentStrategy;



                                                                                                 20
Disposer – Sample Code


@Produces @RequestScoped
Connection connect(User user) {
    return createConnection(user.getId(), user.getPassword());
}


void close(@Disposes Connection connection) {
    connection.close();
}




                                                                 21
Interceptors

• Two interception points on a target class
   – Business method
   – Lifecycle callback
• Cross-cutting concerns: logging, auditing, profiling
• Different from EJB 3.0 Interceptors
    – Type-safe, Enablement/ordering via beans.xml, ...
• Defined using annotations and DD
• Class & Method Interceptors
    – In the same transaction & security context
•
                                                          22
Interceptors – Business Method (Logging)

@InterceptorBinding                                   @LoggingInterceptorBinding
                                                      public class MyManagedBean {
@Retention(RUNTIME)                                     . . .
@Target({METHOD,TYPE})                                }
public @interface LoggingInterceptorBinding {
}


@Interceptor
@LoggingInterceptorBinding
public class @LogInterceptor {
  @AroundInvoke
  public Object log(InvocationContext context) {
     System.out.println(context.getMethod().getName());
     System.out.println(context.getParameters());
     return context.proceed();
  }
}




                                                                                     23
Interceptors – Business Method (Transaction)

@InterceptorBinding                                       @Transactional
                                                          public class ShoppingCart { . . . }
@Retention(RUNTIME)
@Target({METHOD,TYPE})
public @interface Transactional {                         public class ShoppingCart {
}                                                           @Transactional public void checkOut() { . . . }


@Interceptor
@Transactional
public class @TransactionInterceptor {
  @Resource UserTransaction tx;
  @AroundInvoke
  public Object manageTransaction(InvocationContext context) {
    tx.begin()
    context.proceed();
    tx.commit();
  }
}

http://blogs.sun.com/arungupta/entry/totd_151_transactional_interceptors_using


                                                                                                              24
Decorators

• Complimentary to Interceptors
• Apply to beans of a particular bean type
  – Semantic aware of the business method
  – Implement “business concerns”
• Disabled by default, enabled in “beans.xml”
  – May be enabled/disabled at deployment time
• @Delegate – injection point for the same type as the beans
  they decorate
• Interceptors are called before decorators

                                                               25
Decorator – Sample Code
public interface Account {                  @Decorator
 public BigDecimal getBalance();            public abstract class LargeTransactionDecorator
 public User getOwner();                       implements Account {
 public void withdraw(BigDecimal amount);
 public void deposit(BigDecimal amount);        @Inject @Delegate @Any Account account;
}                                               @PersistenceContext EntityManager em;

                                                public void withdraw(BigDecimal amount) {
<beans ...
                                                  …
 <decorators>
                                                }
  <class>
    org.example.LargeTransactionDecorator       public void deposit(BigDecimal amount);
  </class>                                        …
                                                }
 </decorators>
                                            }
</beans>


                                                                                              26
Alternatives

• Deployment time polymorphism
• @Alternative beans are unavailable for injection, lookup or
  EL resolution
  – Bean specific to a client module or deployment scenario
• Need to be explicitly enabled in “beans.xml” using
  <alternatives>/<class>




                                                                27
Events – More decoupling
• Annotation-based event model
    – Based upon “Observer” pattern
•   A “producer” bean fires an event
•   An “observer” bean watches an event
•   Events can have qualifiers
•   Transactional event observers
    – IN_PROGRESS, AFTER_SUCCESS, AFTER_FAILURE,
      AFTER_COMPLETION, BEFORE_COMPLETION




                                                   28
Events – Sample Code
@Inject @Any Event<PrintEvent> myEvent;

void print() {
  . . .
  myEvent.fire(new PrintEvent(5));
}
void onPrint(@Observes PrintEvent event){…}
public class PrintEvent {
  public PrintEvent(int pages) {
    this.pages = pages;
  }
  . . .
}

void addProduct(@Observes(during = AFTER_SUCCESS) @Created
Product product)
                                                             29
Stereotypes

• Encapsulate architectural patterns or common metadata in a
  central place
  – Encapsulates properties of the role – scope, interceptor bindings,
    qualifiers, etc.
• Pre-defined stereotypes - @Interceptor, @Decorator,
  @Model
• “Stereotype stacking”




                                                                         30
Stereotypes – Sample Code (Pre-defined)

@Named
@RequestScoped
@Stereotype
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface Model {}




• Use @Model on JSF “backing beans”


                                           31
Stereotypes – Sample Code (Make Your Own)

@RequestScoped
@Transactional(requiresNew=true)
@Secure
@Named
@Stereotype
@Retention(RUNTIME)
@Target(TYPE)
public @interface Action {}




                                            32
Loose Coupling

• Alternatives – deployment time polymorphism
• Producer – runtime polymorphism
• Interceptors – decouple technical and business concerns
• Decorators – decouple business concerns
• Event notifications – decouple event producer and
  consumers
• Contextual lifecycle management decouples bean
  lifecycles


                                                            33
Strong Typing

• No String-based identifiers, only type-safe Java constructs
  – Dependencies, interceptors, decorators, event produced/consumed, ...
• IDEs can provide autocompletion, validation, and refactoring
• Lift the semantic level of code
  – Make the code more understandable
  – @Asynchronous instead of asyncPaymentProcessor
• Stereotypes




                                                                           34
CDI & EJB - Typesafety


• Java EE resources injected using String-based names (non-
typesafe)
• JDBC/JMS resources, EJB references, Persistence
Context/Unit, …
• Typesafe dependency injection
• Loose coupling, Strong typing
• Lesser errors due to typos in String-based names
• Easier and better tooling



                                                              35
CDI & EJB – Stateful Components



• Stateful components passed by client in a scope
• Explicitly destroy components when the scope is complete


• Session bean through CDI is “contextual instance”
• CDI runtime creates the instance when needed by the client
• CDI runtime destroys the instance when the context ends




                                                               36
CDI & EJB – As JSF “backing bean”



•JSF managed beans used as “glue” to connect with Java EE enterprise
services



• EJB may be used as JSF managed beans
 • No JSF backing beans “glue”
• Brings transactional support to web tier




                                                                       37
CDI & EJB – Enhanced Interceptors


• Interceptors only defined for session beans or message
listener methods of MDBs
• Enabled statically using “ejb-jar.xml” or @Interceptors

• Typesafe Interceptor bindings on any managed bean
• Can be enabled or disabled at deployment using “beans.xml”
• Order of interceptors can be controlled using “beans.xml”




                                                               38
CDI & JSF


• Brings transactional support to web tier by allowing EJB as JSF
  “backing beans”
• Built-in stereotypes for ease-of-development - @Model
• Integration with Unified Expression Language
  – <h:dataTable value=#{cart.lineItems}” var=”item”>
• Context management complements JSF's component-oriented
  model



                                                                39
CDI & JSF


• @ConversationScope holds state with a browser tab in JSF
  application
  – @Inject Conversation conv;
• Transient (default) and long-running conversations
    • Shopping Cart example
    • Transient converted to long-running: Conversation.begin/end
• @Named enables EL-friendly name



                                                                    40
CDI & JPA

      • Typesafe dependency injection of PersistenceContext &
        PersistenceUnit using @Produces
            – Single place to unify all component references

               @PersistenceContext(unitName=”...”) EntityManager em;

                  @Produces @PersistenceContext(unitName=”...”)
 CDI                      @CustomerDatabase EntityManager em;
Qualifier

              @Inject @CustomerDatabase EntityManager em;




                                                                       41
CDI & JPA


• Create “transactional event observers”
  – Kinds
    •   IN_PROGRESS
    •   BEFORE_COMPLETION
    •   AFTER_COMPLETION
    •   AFTER_FAILURE
    •   AFTER_SUCCESS
  – Keep the cache updated




                                           42
CDI & JAX-RS


• Manage the lifecycle of JAX-RS resource by CDI
  – Annotate a JAX-RS resource with @RequestScoped
• @Path to convert class of a managed component into a
  root resource class




                                                         43
CDI & JAX-WS

• Typesafe dependency injection of @WebServiceRef using
  @Produces
@Produces
@WebServiceRef(lookup="java:app/service/PaymentService")
PaymentService paymentService;

@Inject PaymentService remotePaymentService;
• @Inject can be used in Web Service Endpoints & Handlers
• Scopes during Web service invocation
  – RequestScope during request invocation
  – ApplicationScope during any Web service invocation
                                                            44
Portable Extensions

• Key development around Java EE 6 “extensibility” theme
• Addition of beans, decorators, interceptors, contexts
  – OSGi service into Java EE components
  – Running CDI in Java SE environment
  – TX and Persistence to non-EJB managed beans
• Integration with BPM engines
• Integration with 3 -party frameworks like Spring, Seam, Wicket
                    rd


• New technology based upon the CDI programming model



                                                                   45
Portable Extensions – Weld Bootstrapping in Java SE


public class HelloWorld {
  public void printHello(@Observes ContainerInitialized event,
                          @Parameters List<String> parameters) {
      System.out.println("Hello" + parameters.get(0));
  }
}




                                                                   46
Portable Extensions – Weld Logger


public class Checkout {
   @Inject Logger log;

    public void invoiceItems() {
       ShoppingCart cart;
       ...
       log.debug("Items invoiced for {}", cart);

    }
}




                                                   47
Portable Extensions – Typesafe injection of OSGi Service

   • org.glassfish.osgi-cdi – portable extensionin
     GlassFish 3.1
   • Intercepts deployment of hybrid applications
   • Discover (using criteria), bind, track, inject the service
   • Metadata – filter, wait timeouts, dynamic binding




http://blogs.sun.com/sivakumart/entry/typesafe_injection_of_dynamic_osgi


                                                                           48
CDI 1.1 (JSR TBD)
    http://lists.jboss.org/pipermail/weld-dev/2011-February/002847.html
                                                                          NEW

•    Global ordering of interceptors and decorators
•    API for managing built-in contexts
•    Embedded mode to startup outside Java EE container
•    Send Servlet events as CDI events
•    ...




                                                                                49
CDI Implementations




                      50
IDE Support




              51
IDE Support

          • Inspect Observer/Producer for a given event




http://wiki.netbeans.org/NewAndNoteworthyNB70#CDI


                                                          52
IDE Support




http://blogs.jetbrains.com/idea/2009/11/cdi-jsr-299-run-with-me/


                                                                   53
IDE Support




http://docs.jboss.org/tools/whatsnew/


                                        54
IDE Support




http://docs.jboss.org/tools/whatsnew/


                                        55
Summary


• Provides standards-based and typesafe dependency injection
  in Java EE 6
• Integrates well with other Java EE 6 technologies
• Portable Extensions facilitate richer programming model
• Weld is the Reference Implementation
   – Integrated in GlassFish and JBoss
• Improving support in IDEs



                                                               56
References


•   oracle.com/goto/glassfish
•   glassfish.org
•   blogs.sun.com/theaquarium
•   youtube.com/user/GlassFishVideos
•   http://docs.jboss.org/weld/reference/latest/en-US/html/
•   Follow @glassfish




                                                              57
<Insert Picture Here>




Contexts And Dependency Injection In The Java EE 6 Ecosystem
Arun Gupta, Java EE & GlassFish Guy
blogs.sun.com/arungupta, @arungupta

More Related Content

PDF
Using Contexts & Dependency Injection in the Java EE 6 Platform
ODP
CDI @javaonehyderabad
PPT
Contexts and Dependency Injection for the JavaEE platform
PDF
S313937 cdi dochez
PPT
PDF
S313431 JPA 2.0 Overview
PPTX
Introduction to JPA (JPA version 2.0)
PPT
Java Persistence API (JPA) Step By Step
Using Contexts & Dependency Injection in the Java EE 6 Platform
CDI @javaonehyderabad
Contexts and Dependency Injection for the JavaEE platform
S313937 cdi dochez
S313431 JPA 2.0 Overview
Introduction to JPA (JPA version 2.0)
Java Persistence API (JPA) Step By Step

What's hot (20)

PDF
Hibernate Interview Questions
PDF
Introduction To Web Beans
PPTX
Technical Interview
PDF
Java Persistence API 2.0: An Overview
PPTX
Java Beans
PDF
Rich Internet Applications con JavaFX e NetBeans
ODP
Hibernate complete Training
PPT
07 association of entities
PDF
Java persistence api 2.1
PPTX
JPA For Beginner's
PDF
Introduction to JPA and Hibernate including examples
PPT
06 association of value types
PPT
jpa-hibernate-presentation
PDF
PPT
15 jpaql
PDF
Bea weblogic job_interview_preparation_guide
DOCX
Hibernate3 q&a
PDF
Java j2ee interview_questions
PDF
CDI and Weld
PDF
JPA and Hibernate
Hibernate Interview Questions
Introduction To Web Beans
Technical Interview
Java Persistence API 2.0: An Overview
Java Beans
Rich Internet Applications con JavaFX e NetBeans
Hibernate complete Training
07 association of entities
Java persistence api 2.1
JPA For Beginner's
Introduction to JPA and Hibernate including examples
06 association of value types
jpa-hibernate-presentation
15 jpaql
Bea weblogic job_interview_preparation_guide
Hibernate3 q&a
Java j2ee interview_questions
CDI and Weld
JPA and Hibernate
Ad

Similar to Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem (20)

PPTX
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
PPTX
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
PDF
Make JSF more type-safe with CDI and MyFaces CODI
PPTX
Java EE 6
PPTX
Introduction to CDI
PPTX
Introduction to CDI and DI in Java EE 6
PDF
CDI Best Practices with Real-Life Examples - TUT3287
PPTX
Context and Dependency Injection 2.0
PDF
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
PDF
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
PDF
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
PDF
Contextual Dependency Injection for Apachecon 2010
PPTX
Spring data jpa
PDF
RESTful Web services using JAX-RS
PDF
springdatajpa-up.pdf
PPTX
Contexts and Dependency Injection
PDF
Suportando Aplicações Multi-tenancy com Java EE
ODP
Java EE web project introduction
PDF
New Features of JSR 317 (JPA 2.0)
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
Make JSF more type-safe with CDI and MyFaces CODI
Java EE 6
Introduction to CDI
Introduction to CDI and DI in Java EE 6
CDI Best Practices with Real-Life Examples - TUT3287
Context and Dependency Injection 2.0
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Contextual Dependency Injection for Apachecon 2010
Spring data jpa
RESTful Web services using JAX-RS
springdatajpa-up.pdf
Contexts and Dependency Injection
Suportando Aplicações Multi-tenancy com Java EE
Java EE web project introduction
New Features of JSR 317 (JPA 2.0)
Ad

More from Arun Gupta (20)

PDF
5 Skills To Force Multiply Technical Talents.pdf
PPTX
Machine Learning using Kubernetes - AI Conclave 2019
PDF
Machine Learning using Kubeflow and Kubernetes
PPTX
Secure and Fast microVM for Serverless Computing using Firecracker
PPTX
Building Java in the Open - j.Day at OSCON 2019
PPTX
Why Amazon Cares about Open Source
PDF
Machine learning using Kubernetes
PDF
Building Cloud Native Applications
PDF
Chaos Engineering with Kubernetes
PDF
How to be a mentor to bring more girls to STEAM
PDF
Java in a World of Containers - DockerCon 2018
PPTX
The Serverless Tidal Wave - SwampUP 2018 Keynote
PDF
Introduction to Amazon EKS - KubeCon 2018
PDF
Mastering Kubernetes on AWS - Tel Aviv Summit
PDF
Top 10 Technology Trends Changing Developer's Landscape
PDF
Container Landscape in 2017
PDF
Java EE and NoSQL using JBoss EAP 7 and OpenShift
PDF
Docker, Kubernetes, and Mesos recipes for Java developers
PDF
Thanks Managers!
PDF
Migrate your traditional VM-based Clusters to Containers
5 Skills To Force Multiply Technical Talents.pdf
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubeflow and Kubernetes
Secure and Fast microVM for Serverless Computing using Firecracker
Building Java in the Open - j.Day at OSCON 2019
Why Amazon Cares about Open Source
Machine learning using Kubernetes
Building Cloud Native Applications
Chaos Engineering with Kubernetes
How to be a mentor to bring more girls to STEAM
Java in a World of Containers - DockerCon 2018
The Serverless Tidal Wave - SwampUP 2018 Keynote
Introduction to Amazon EKS - KubeCon 2018
Mastering Kubernetes on AWS - Tel Aviv Summit
Top 10 Technology Trends Changing Developer's Landscape
Container Landscape in 2017
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Docker, Kubernetes, and Mesos recipes for Java developers
Thanks Managers!
Migrate your traditional VM-based Clusters to Containers

Recently uploaded (20)

PDF
KodekX | Application Modernization Development
PDF
cuic standard and advanced reporting.pdf
PPT
Teaching material agriculture food technology
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Electronic commerce courselecture one. Pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Approach and Philosophy of On baking technology
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Spectroscopy.pptx food analysis technology
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
KodekX | Application Modernization Development
cuic standard and advanced reporting.pdf
Teaching material agriculture food technology
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Electronic commerce courselecture one. Pdf
20250228 LYD VKU AI Blended-Learning.pptx
Big Data Technologies - Introduction.pptx
Understanding_Digital_Forensics_Presentation.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
sap open course for s4hana steps from ECC to s4
Approach and Philosophy of On baking technology
Chapter 3 Spatial Domain Image Processing.pdf
Unlocking AI with Model Context Protocol (MCP)
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Network Security Unit 5.pdf for BCA BBA.
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectroscopy.pptx food analysis technology
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Diabetes mellitus diagnosis method based random forest with bat algorithm

Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem

  • 1. <Insert Picture Here> Contexts And Dependency Injection In The Java EE 6 Ecosystem Arun Gupta, Java EE & GlassFish Guy blogs.sun.com/arungupta, @arungupta
  • 2. The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle’s products remains at the sole discretion of Oracle. 2
  • 3. How we got here ? • Java EE 5 had resource injection – @EJB, @PersistenceUnit, @Resource • Motivated by Seam, Guice, and Spring – More typesafe than Seam – More stateful and less XML-centric than Spring – More web and enterprise-capable than Guice • Adapts JSR 330 for Java EE environments – @Inject, @Qualifier, @ScopeType 3
  • 4. CDI Key Concepts • Type-safe approach to Dependency Injection • Strong typing, Loose coupling – Events, Interceptors, Decorators • Context & Scope management • Works with Java EE modular and component architecture – Integration with Unified Expression Language (UEL) • Portable extensions • Bridge EJB (transactional tier) and JSF (presentation tier) in the platform 4
  • 5. What is a CDI managed bean ? • “Beans” – All managed beans by other Java EE specifications • Except JPA – Meets the following conditions • Non-static inner class • Concrete class or decorated with @Decorator • Constructor with no parameters or a constructor annotated with @Inject • “Contextual instances” - Instances of “beans” that belong to contexts 5
  • 6. How to configure ? There is none! • Discovers bean in all modules in which CDI is enabled • “beans.xml” – WEB-INF of WAR – META-INF of JAR – META-INF of directory in the classpath • Can enable groups of bean selectively via a descriptor 6
  • 7. Injection Points • Field, Method, Constructor • 0 or more qualifiers Which one ? • Type (Qualifier) @Inject @LoggedIn User user Request What ? Injection (Type) 7
  • 8. Basic – Sample Code public interface Greeting { public String sayHello(String name); Default “dependent” scope } public class HelloGreeting implements Greeting { public String sayHello(String name) { return “Hello “ + name; } } @Stateless public class GreetingService { @Inject Greeting greeting; public String sayHello(String name) { No String identifiers, return greeting.sayHello(name); All Java } } 8
  • 9. Qualifier • Annotation to uniquely identify a bean to be injected • Built-in qualifiers – @Named required for usage in EL – @Default qualifier on all beans marked with/without @Named – @Any implicit qualifier for all beans (except @New) – @New 9
  • 10. Qualifier – Sample Code @Qualifier @Retention(RUNTIME) @Target({METHOD, FIELD, PARAMETER, TYPE}) public @interface Texan { } @Texan public class HowdyGreeting implements Greeting { public String sayHello(String name) { return “Howdy “ + name; } } @Stateless public class GreetingService { @Inject @Texan Greeting greeting; public String sayHello(String name) { return greeting.sayHello(name); } } 10
  • 11. Field and Method Injection public class CheckoutHandler { @Inject @LoggedIn User user; @Inject PaymentProcessor processor; @Inject void setShoppingCart(@Default Cart cart) { … } } 11
  • 12. Constructor Injection public class CheckoutHandler { @Inject CheckoutHandler(@LoggedIn User user, PaymentProcessor processor, Cart cart) { ... } } • Only one constructor can have @Inject • Makes the bean immutable 12
  • 13. Multiple Qualifiers and Qualifiers with Arguments public class CheckoutHandler { @Inject CheckoutHandler(@LoggedIn User user, @Reliable @PayBy(CREDIT_CARD) PaymentProcessor processor, @Default Cart cart) { ... } } 13
  • 14. Typesafe Resolution • Resolution is performed at system initialization time • @Qualifier, @Alternative – Unsatisfied dependency • Create a bean which implements the bean type with all qualifiers • Explicitly enable an @Alternative bean using beans.xml • Make sure it is in the classpath – Ambiguous dependency • Introduce a qualifier • Disable one of the beans using @Alternative • Move one implementation out of classpath 14
  • 15. Client Proxies • Container indirects all injected references through a proxy object unless it is @Dependent • Proxies may be shared between multiple injection points @ApplicationScoped @RequestScoped public class UserService { public class User { private String message; @Inject User user; // getter & setter } public void doSomething() { user.setMessage("..."); // some other stuff user.getMessage(); } } 15
  • 16. Scopes • Beans can be declared in a scope – Everywhere: @ApplicationScoped, @RequestScoped – Web app: @SessionScoped (must be serializable) – JSF app: @ConversationScoped • Transient and long-running – Pseudo-scope (default): @Dependent – Custom scopes via @Scope • Runtime makes sure the right bean is created at the right time • Client do NOT have to be scope-aware 16
  • 17. ConversationScope – Sample Code • Like session-scope – spans multiple requests to the server • Unlike – demarcated explicitly by the application, holds state with a particular browser tab in a JSF application public class ShoppingService { @Inject Conversation conv; public void startShopping() { conv.begin(); } . . . public void checkOut() { conv.end(); } } 17
  • 18. Custom Scopes – Sample Code @ScopeType @Retention(RUNTIME) @Target({TYPE, METHOD}) public @interface ClusterScoped {} public @interface TransactionScoped {} public @interface ThreadScoped {} 18
  • 19. Producer & Disposer • Producer – Exposes any non-bean class as a bean, e.g. a JPA entity – Bridge the gap with Java EE DI – Perform custom initialization not possible in a constructor – Define multiple beans, with different scopes or initialization, for the same implementation class – Method or field – Runtime polymorphism • Disposer – cleans up the “produced” object – e.g. explicitly closing JDBC connection – Defined in the same class as the “producer” method 19
  • 20. Producer – Sample Code @SessionScoped public class Preferences implements Serializable { How often the method is called, private PaymentStrategyType paymentStrategy; Lifecycle of the objects returned . . . Default is @Dependent @Produces @Preferred @SessionScoped public PaymentStrategy getPaymentStrategy() { switch (paymentStrategy) { case CREDIT_CARD: return new CreditCardPaymentStrategy(); case CHECK: return new CheckPaymentStrategy(); case PAYPAL: return new PayPalPaymentStrategy(); default: return null; } } } @Inject @Preferred PaymentStrategy paymentStrategy; 20
  • 21. Disposer – Sample Code @Produces @RequestScoped Connection connect(User user) { return createConnection(user.getId(), user.getPassword()); } void close(@Disposes Connection connection) { connection.close(); } 21
  • 22. Interceptors • Two interception points on a target class – Business method – Lifecycle callback • Cross-cutting concerns: logging, auditing, profiling • Different from EJB 3.0 Interceptors – Type-safe, Enablement/ordering via beans.xml, ... • Defined using annotations and DD • Class & Method Interceptors – In the same transaction & security context • 22
  • 23. Interceptors – Business Method (Logging) @InterceptorBinding @LoggingInterceptorBinding public class MyManagedBean { @Retention(RUNTIME) . . . @Target({METHOD,TYPE}) } public @interface LoggingInterceptorBinding { } @Interceptor @LoggingInterceptorBinding public class @LogInterceptor { @AroundInvoke public Object log(InvocationContext context) { System.out.println(context.getMethod().getName()); System.out.println(context.getParameters()); return context.proceed(); } } 23
  • 24. Interceptors – Business Method (Transaction) @InterceptorBinding @Transactional public class ShoppingCart { . . . } @Retention(RUNTIME) @Target({METHOD,TYPE}) public @interface Transactional { public class ShoppingCart { } @Transactional public void checkOut() { . . . } @Interceptor @Transactional public class @TransactionInterceptor { @Resource UserTransaction tx; @AroundInvoke public Object manageTransaction(InvocationContext context) { tx.begin() context.proceed(); tx.commit(); } } http://blogs.sun.com/arungupta/entry/totd_151_transactional_interceptors_using 24
  • 25. Decorators • Complimentary to Interceptors • Apply to beans of a particular bean type – Semantic aware of the business method – Implement “business concerns” • Disabled by default, enabled in “beans.xml” – May be enabled/disabled at deployment time • @Delegate – injection point for the same type as the beans they decorate • Interceptors are called before decorators 25
  • 26. Decorator – Sample Code public interface Account { @Decorator public BigDecimal getBalance(); public abstract class LargeTransactionDecorator public User getOwner(); implements Account { public void withdraw(BigDecimal amount); public void deposit(BigDecimal amount); @Inject @Delegate @Any Account account; } @PersistenceContext EntityManager em; public void withdraw(BigDecimal amount) { <beans ... … <decorators> } <class> org.example.LargeTransactionDecorator public void deposit(BigDecimal amount); </class> … } </decorators> } </beans> 26
  • 27. Alternatives • Deployment time polymorphism • @Alternative beans are unavailable for injection, lookup or EL resolution – Bean specific to a client module or deployment scenario • Need to be explicitly enabled in “beans.xml” using <alternatives>/<class> 27
  • 28. Events – More decoupling • Annotation-based event model – Based upon “Observer” pattern • A “producer” bean fires an event • An “observer” bean watches an event • Events can have qualifiers • Transactional event observers – IN_PROGRESS, AFTER_SUCCESS, AFTER_FAILURE, AFTER_COMPLETION, BEFORE_COMPLETION 28
  • 29. Events – Sample Code @Inject @Any Event<PrintEvent> myEvent; void print() { . . . myEvent.fire(new PrintEvent(5)); } void onPrint(@Observes PrintEvent event){…} public class PrintEvent { public PrintEvent(int pages) { this.pages = pages; } . . . } void addProduct(@Observes(during = AFTER_SUCCESS) @Created Product product) 29
  • 30. Stereotypes • Encapsulate architectural patterns or common metadata in a central place – Encapsulates properties of the role – scope, interceptor bindings, qualifiers, etc. • Pre-defined stereotypes - @Interceptor, @Decorator, @Model • “Stereotype stacking” 30
  • 31. Stereotypes – Sample Code (Pre-defined) @Named @RequestScoped @Stereotype @Target({TYPE, METHOD}) @Retention(RUNTIME) public @interface Model {} • Use @Model on JSF “backing beans” 31
  • 32. Stereotypes – Sample Code (Make Your Own) @RequestScoped @Transactional(requiresNew=true) @Secure @Named @Stereotype @Retention(RUNTIME) @Target(TYPE) public @interface Action {} 32
  • 33. Loose Coupling • Alternatives – deployment time polymorphism • Producer – runtime polymorphism • Interceptors – decouple technical and business concerns • Decorators – decouple business concerns • Event notifications – decouple event producer and consumers • Contextual lifecycle management decouples bean lifecycles 33
  • 34. Strong Typing • No String-based identifiers, only type-safe Java constructs – Dependencies, interceptors, decorators, event produced/consumed, ... • IDEs can provide autocompletion, validation, and refactoring • Lift the semantic level of code – Make the code more understandable – @Asynchronous instead of asyncPaymentProcessor • Stereotypes 34
  • 35. CDI & EJB - Typesafety • Java EE resources injected using String-based names (non- typesafe) • JDBC/JMS resources, EJB references, Persistence Context/Unit, … • Typesafe dependency injection • Loose coupling, Strong typing • Lesser errors due to typos in String-based names • Easier and better tooling 35
  • 36. CDI & EJB – Stateful Components • Stateful components passed by client in a scope • Explicitly destroy components when the scope is complete • Session bean through CDI is “contextual instance” • CDI runtime creates the instance when needed by the client • CDI runtime destroys the instance when the context ends 36
  • 37. CDI & EJB – As JSF “backing bean” •JSF managed beans used as “glue” to connect with Java EE enterprise services • EJB may be used as JSF managed beans • No JSF backing beans “glue” • Brings transactional support to web tier 37
  • 38. CDI & EJB – Enhanced Interceptors • Interceptors only defined for session beans or message listener methods of MDBs • Enabled statically using “ejb-jar.xml” or @Interceptors • Typesafe Interceptor bindings on any managed bean • Can be enabled or disabled at deployment using “beans.xml” • Order of interceptors can be controlled using “beans.xml” 38
  • 39. CDI & JSF • Brings transactional support to web tier by allowing EJB as JSF “backing beans” • Built-in stereotypes for ease-of-development - @Model • Integration with Unified Expression Language – <h:dataTable value=#{cart.lineItems}” var=”item”> • Context management complements JSF's component-oriented model 39
  • 40. CDI & JSF • @ConversationScope holds state with a browser tab in JSF application – @Inject Conversation conv; • Transient (default) and long-running conversations • Shopping Cart example • Transient converted to long-running: Conversation.begin/end • @Named enables EL-friendly name 40
  • 41. CDI & JPA • Typesafe dependency injection of PersistenceContext & PersistenceUnit using @Produces – Single place to unify all component references @PersistenceContext(unitName=”...”) EntityManager em; @Produces @PersistenceContext(unitName=”...”) CDI @CustomerDatabase EntityManager em; Qualifier @Inject @CustomerDatabase EntityManager em; 41
  • 42. CDI & JPA • Create “transactional event observers” – Kinds • IN_PROGRESS • BEFORE_COMPLETION • AFTER_COMPLETION • AFTER_FAILURE • AFTER_SUCCESS – Keep the cache updated 42
  • 43. CDI & JAX-RS • Manage the lifecycle of JAX-RS resource by CDI – Annotate a JAX-RS resource with @RequestScoped • @Path to convert class of a managed component into a root resource class 43
  • 44. CDI & JAX-WS • Typesafe dependency injection of @WebServiceRef using @Produces @Produces @WebServiceRef(lookup="java:app/service/PaymentService") PaymentService paymentService; @Inject PaymentService remotePaymentService; • @Inject can be used in Web Service Endpoints & Handlers • Scopes during Web service invocation – RequestScope during request invocation – ApplicationScope during any Web service invocation 44
  • 45. Portable Extensions • Key development around Java EE 6 “extensibility” theme • Addition of beans, decorators, interceptors, contexts – OSGi service into Java EE components – Running CDI in Java SE environment – TX and Persistence to non-EJB managed beans • Integration with BPM engines • Integration with 3 -party frameworks like Spring, Seam, Wicket rd • New technology based upon the CDI programming model 45
  • 46. Portable Extensions – Weld Bootstrapping in Java SE public class HelloWorld { public void printHello(@Observes ContainerInitialized event, @Parameters List<String> parameters) { System.out.println("Hello" + parameters.get(0)); } } 46
  • 47. Portable Extensions – Weld Logger public class Checkout { @Inject Logger log; public void invoiceItems() { ShoppingCart cart; ... log.debug("Items invoiced for {}", cart); } } 47
  • 48. Portable Extensions – Typesafe injection of OSGi Service • org.glassfish.osgi-cdi – portable extensionin GlassFish 3.1 • Intercepts deployment of hybrid applications • Discover (using criteria), bind, track, inject the service • Metadata – filter, wait timeouts, dynamic binding http://blogs.sun.com/sivakumart/entry/typesafe_injection_of_dynamic_osgi 48
  • 49. CDI 1.1 (JSR TBD) http://lists.jboss.org/pipermail/weld-dev/2011-February/002847.html NEW • Global ordering of interceptors and decorators • API for managing built-in contexts • Embedded mode to startup outside Java EE container • Send Servlet events as CDI events • ... 49
  • 52. IDE Support • Inspect Observer/Producer for a given event http://wiki.netbeans.org/NewAndNoteworthyNB70#CDI 52
  • 56. Summary • Provides standards-based and typesafe dependency injection in Java EE 6 • Integrates well with other Java EE 6 technologies • Portable Extensions facilitate richer programming model • Weld is the Reference Implementation – Integrated in GlassFish and JBoss • Improving support in IDEs 56
  • 57. References • oracle.com/goto/glassfish • glassfish.org • blogs.sun.com/theaquarium • youtube.com/user/GlassFishVideos • http://docs.jboss.org/weld/reference/latest/en-US/html/ • Follow @glassfish 57
  • 58. <Insert Picture Here> Contexts And Dependency Injection In The Java EE 6 Ecosystem Arun Gupta, Java EE & GlassFish Guy blogs.sun.com/arungupta, @arungupta