SlideShare uma empresa Scribd logo
1 de 62
Baixar para ler offline
<Insert Picture Here>




Contexts And Dependency Injection In The Java EE 6 Ecosystem
Arun Gupta
Java EE & GlassFish Guy
blogs.sun.com/arungupta, @arungupta
JavaOne and Oracle Develop
Latin America 2010
December 7–9, 2010




                             2
JavaOne and Oracle Develop
Beijing 2010
December 13–16, 2010




                             3
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.


                                                               4
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



                                                     5
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

                                                                   6
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

                                                                               7
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




                                                           8
Injection Points


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




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

                                                           9
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
    }
}



                                                                             10
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




                                                            11
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);
    }
}




                                                   12
Field and Method Injection


public class CheckoutHandler {

    @Inject @LoggedIn User user;

    @Inject PaymentProcessor processor;

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

}


                                                 13
Constructor Injection


 public class CheckoutHandler {

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

 }

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

                                                   14
Multiple Qualifiers and Qualifiers with Arguments


public class CheckoutHandler {

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

}


                                                    15
Bean Initialization Sequence


1. Default bean constructor or the one annotated with @Inject
2. Values of all injected fields of the beans
3. All initializer methods of the beans
  1.Defined within bean hierarchy
  2. Call order not portable within a single bean
4. @PostConstruct method




                                                                16
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


                                                                         17
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();
    }
}


                                                                18
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


                                                                   19
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();
     }
 }


                                                                   20
Custom Scopes – Sample Code


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

public @interface TransactionScoped {}


public @interface ThreadScoped {}




                                         21
@New Qualifier

• Allows to obtain a dependent object of a specified class,
  independent of declared scope
  – Useful with @Produces

 @ConversationScoped
 public class Calculator { . . .   }



 public class PaymentCalc {
     @Inject Calculator calculator;
     @Inject @New Calculator newCalculator;
 }



                                                              22
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

                                                                              23
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;



                                                                                                 24
Disposer – Sample Code


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


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




                                                                 25
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
•
                                                          26
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();
  }
}




                                                                                     27
Why Interceptor Bindings ?

• Remove dependency from the interceptor implementation class
• Can vary depending upon deployment environment
• Allows central ordering of interceptors




                                                            28
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


                                                                                                              29
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

                                                               30
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>


                                                                                              31
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>




                                                                32
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




                                                   33
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)
                                                             34
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”




                                                                         35
Stereotypes – Sample Code (Pre-defined)

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




• Use @Model on JSF “backing beans”


                                           36
Stereotypes – Sample Code (Make Your Own)

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




                                            37
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


                                                            38
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




                                                                           39
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



                                                              40
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




                                                               41
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




                                                                       42
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”




                                                               43
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



                                                                44
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



                                                                    45
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;




                                                                       46
CDI & JPA


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




                                           47
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




                                                         48
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
                                                            49
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



                                                                   50
Portable Extension – How to author ?

• Implement javax.enterprise.inject.spi.Extension
  SPI
  – Register service provider
• Observe container lifecycle events
  – Before/AfterBeanDiscovery, ProcessAnnotatedType
• Ways to integrate with container
  –   Provide beans, interceptors, or decorators
  –   Satisfy injection points with built-in or wrapped types
  –   Contribute a scope and context implementation
  –   Augment or override annotation metadata

                                                                51
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));
  }
}




                                                                   52
Portable Extensions – Weld Logger


public class Checkout {
   @Inject Logger log;

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

    }
}




                                                   53
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


                                                                           54
CDI Implementations




                      55
IDE Support




              56
IDE Support

          • Inspect Observer/Producer for a given event




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


                                                          57
IDE Support




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


                                                                   58
IDE Support




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


                                        59
IDE Support




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


                                        60
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



                                                               61
References


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




                                                              62

Mais conteĂşdo relacionado

Mais procurados

Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)Fahad Golra
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview QuestionsSyed Shahul
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOPHitesh-Java
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guidePankaj Singh
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Fahad Golra
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in javaAcp Jamod
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEmprovise
 
Ecom lec3 16_ej_bs
Ecom lec3 16_ej_bsEcom lec3 16_ej_bs
Ecom lec3 16_ej_bsZainab Khallouf
 
Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Armen Arzumanyan
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer ReferenceMuthuselvam RS
 
Java interview questions
Java interview questionsJava interview questions
Java interview questionsSoba Arjun
 
Session 3 Tp3
Session 3 Tp3Session 3 Tp3
Session 3 Tp3phanleson
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization Hitesh-Java
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersWhizlabs
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-finalRohit Kelapure
 
EJB3 Advance Features
EJB3 Advance FeaturesEJB3 Advance Features
EJB3 Advance FeaturesEmprovise
 

Mais procurados (20)

Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
 
EJB .
EJB .EJB .
EJB .
 
Hibernate Interview Questions
Hibernate Interview QuestionsHibernate Interview Questions
Hibernate Interview Questions
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
 
Java EE EJB Applications
Java EE EJB ApplicationsJava EE EJB Applications
Java EE EJB Applications
 
Ejb3 Presentation
Ejb3 PresentationEjb3 Presentation
Ejb3 Presentation
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in java
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business Logic
 
Ecom lec3 16_ej_bs
Ecom lec3 16_ej_bsEcom lec3 16_ej_bs
Ecom lec3 16_ej_bs
 
Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Session 3 Tp3
Session 3 Tp3Session 3 Tp3
Session 3 Tp3
 
EJB 3.0 and J2EE
EJB 3.0 and J2EEEJB 3.0 and J2EE
EJB 3.0 and J2EE
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Top 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed AnswersTop 100 Java Interview Questions with Detailed Answers
Top 100 Java Interview Questions with Detailed Answers
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
 
EJB3 Advance Features
EJB3 Advance FeaturesEJB3 Advance Features
EJB3 Advance Features
 

Destaque

[Java] Contexts and Dependency Injection em JEE6
[Java] Contexts and Dependency Injection em JEE6[Java] Contexts and Dependency Injection em JEE6
[Java] Contexts and Dependency Injection em JEE6Jose Naves Moura Neto
 
The Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the CloudThe Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the Cloudcodemotion_es
 
Cloud ios alternativas
Cloud ios alternativasCloud ios alternativas
Cloud ios alternativascodemotion_es
 
Designing Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIDesigning Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIMichel Graciano
 
Dependency injection
Dependency injectionDependency injection
Dependency injectionEugenio Lentini
 
Practical introduction to dependency injection
Practical introduction to dependency injectionPractical introduction to dependency injection
Practical introduction to dependency injectionTamas Rev
 

Destaque (6)

[Java] Contexts and Dependency Injection em JEE6
[Java] Contexts and Dependency Injection em JEE6[Java] Contexts and Dependency Injection em JEE6
[Java] Contexts and Dependency Injection em JEE6
 
The Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the CloudThe Java EE 7 Platform: Developing for the Cloud
The Java EE 7 Platform: Developing for the Cloud
 
Cloud ios alternativas
Cloud ios alternativasCloud ios alternativas
Cloud ios alternativas
 
Designing Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDIDesigning Java EE Applications in the Age of CDI
Designing Java EE Applications in the Age of CDI
 
Dependency injection
Dependency injectionDependency injection
Dependency injection
 
Practical introduction to dependency injection
Practical introduction to dependency injectionPractical introduction to dependency injection
Practical introduction to dependency injection
 

Semelhante a Using Contexts & Dependency Injection in the Java EE 6 Platform

S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochezJerome Dochez
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDIJim Bethancourt
 
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)Kevin Sutter
 
CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287Ahmad Gohar
 
Make JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIMake JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIos890
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introductionOndrej MihĂĄlyi
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-finalRohit Kelapure
 
Context and Dependency Injection
Context and Dependency InjectionContext and Dependency Injection
Context and Dependency InjectionWerner Keil
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Ray Ploski
 
Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Brian S. Paskin
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaArun Gupta
 
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Miguel Gallardo
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)Markus Eisele
 
S313431 JPA 2.0 Overview
S313431 JPA 2.0 OverviewS313431 JPA 2.0 Overview
S313431 JPA 2.0 OverviewLudovic Champenois
 
Prince st Tech Talk - MABI Framework
Prince st Tech Talk - MABI FrameworkPrince st Tech Talk - MABI Framework
Prince st Tech Talk - MABI FrameworkPhotis Patriotis
 

Semelhante a Using Contexts & Dependency Injection in the Java EE 6 Platform (20)

CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
Introduction To Web Beans
Introduction To Web BeansIntroduction To Web Beans
Introduction To Web Beans
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
CDI in JEE6
CDI in JEE6CDI in JEE6
CDI in JEE6
 
Java EE 6
Java EE 6Java EE 6
Java EE 6
 
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
 
CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287CDI Best Practices with Real-Life Examples - TUT3287
CDI Best Practices with Real-Life Examples - TUT3287
 
Make JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODIMake JSF more type-safe with CDI and MyFaces CODI
Make JSF more type-safe with CDI and MyFaces CODI
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
 
Context and Dependency Injection
Context and Dependency InjectionContext and Dependency Injection
Context and Dependency Injection
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
 
Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Context and Dependency Injection 2.0
Context and Dependency Injection 2.0
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
 
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
Code decoupling from Symfony (and others frameworks) - PHP Conference Brasil ...
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
 
S313431 JPA 2.0 Overview
S313431 JPA 2.0 OverviewS313431 JPA 2.0 Overview
S313431 JPA 2.0 Overview
 
Prince st Tech Talk - MABI Framework
Prince st Tech Talk - MABI FrameworkPrince st Tech Talk - MABI Framework
Prince st Tech Talk - MABI Framework
 
Prince sttalkv5
Prince sttalkv5Prince sttalkv5
Prince sttalkv5
 

Mais de Arun Gupta

5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdf5 Skills To Force Multiply Technical Talents.pdf
5 Skills To Force Multiply Technical Talents.pdfArun Gupta
 
Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Machine Learning using Kubernetes - AI Conclave 2019
Machine Learning using Kubernetes - AI Conclave 2019Arun Gupta
 
Machine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesMachine Learning using Kubeflow and Kubernetes
Machine Learning using Kubeflow and KubernetesArun Gupta
 
Secure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerSecure and Fast microVM for Serverless Computing using Firecracker
Secure and Fast microVM for Serverless Computing using FirecrackerArun Gupta
 
Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Building Java in the Open - j.Day at OSCON 2019
Building Java in the Open - j.Day at OSCON 2019Arun Gupta
 
Why Amazon Cares about Open Source
Why Amazon Cares about Open SourceWhy Amazon Cares about Open Source
Why Amazon Cares about Open SourceArun Gupta
 
Machine learning using Kubernetes
Machine learning using KubernetesMachine learning using Kubernetes
Machine learning using KubernetesArun Gupta
 
Building Cloud Native Applications
Building Cloud Native ApplicationsBuilding Cloud Native Applications
Building Cloud Native ApplicationsArun Gupta
 
Chaos Engineering with Kubernetes
Chaos Engineering with KubernetesChaos Engineering with Kubernetes
Chaos Engineering with KubernetesArun Gupta
 
How to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMHow to be a mentor to bring more girls to STEAM
How to be a mentor to bring more girls to STEAMArun Gupta
 
Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Java in a World of Containers - DockerCon 2018
Java in a World of Containers - DockerCon 2018Arun Gupta
 
The Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteThe Serverless Tidal Wave - SwampUP 2018 Keynote
The Serverless Tidal Wave - SwampUP 2018 KeynoteArun Gupta
 
Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Introduction to Amazon EKS - KubeCon 2018
Introduction to Amazon EKS - KubeCon 2018Arun Gupta
 
Mastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitMastering Kubernetes on AWS - Tel Aviv Summit
Mastering Kubernetes on AWS - Tel Aviv SummitArun Gupta
 
Top 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeTop 10 Technology Trends Changing Developer's Landscape
Top 10 Technology Trends Changing Developer's LandscapeArun Gupta
 
Container Landscape in 2017
Container Landscape in 2017Container Landscape in 2017
Container Landscape in 2017Arun Gupta
 
Java EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftJava EE and NoSQL using JBoss EAP 7 and OpenShift
Java EE and NoSQL using JBoss EAP 7 and OpenShiftArun Gupta
 
Docker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersDocker, Kubernetes, and Mesos recipes for Java developers
Docker, Kubernetes, and Mesos recipes for Java developersArun Gupta
 
Thanks Managers!
Thanks Managers!Thanks Managers!
Thanks Managers!Arun Gupta
 
Migrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersMigrate your traditional VM-based Clusters to Containers
Migrate your traditional VM-based Clusters to ContainersArun Gupta
 

Mais de Arun Gupta (20)

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

Último

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Último (20)

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Using Contexts & Dependency Injection in the Java EE 6 Platform

  • 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. JavaOne and Oracle Develop Latin America 2010 December 7–9, 2010 2
  • 3. JavaOne and Oracle Develop Beijing 2010 December 13–16, 2010 3
  • 4. 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. 4
  • 5. 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 5
  • 6. 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 6
  • 7. 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 7
  • 8. 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 8
  • 9. Injection Points • Field, Method, Constructor • 0 or more qualifiers Which one ? • Type (Qualifier) @Inject @LoggedIn User user Request What ? Injection (Type) 9
  • 10. 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 } } 10
  • 11. 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 11
  • 12. 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); } } 12
  • 13. Field and Method Injection public class CheckoutHandler { @Inject @LoggedIn User user; @Inject PaymentProcessor processor; @Inject void setShoppingCart(@Default Cart cart) { … } } 13
  • 14. Constructor Injection public class CheckoutHandler { @Inject CheckoutHandler(@LoggedIn User user, PaymentProcessor processor, Cart cart) { ... } } • Only one constructor can have @Inject • Makes the bean immutable 14
  • 15. Multiple Qualifiers and Qualifiers with Arguments public class CheckoutHandler { @Inject CheckoutHandler(@LoggedIn User user, @Reliable @PayBy(CREDIT_CARD) PaymentProcessor processor, @Default Cart cart) { ... } } 15
  • 16. Bean Initialization Sequence 1. Default bean constructor or the one annotated with @Inject 2. Values of all injected fields of the beans 3. All initializer methods of the beans 1.Defined within bean hierarchy 2. Call order not portable within a single bean 4. @PostConstruct method 16
  • 17. 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 17
  • 18. 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(); } } 18
  • 19. 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 19
  • 20. 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(); } } 20
  • 21. Custom Scopes – Sample Code @ScopeType @Retention(RUNTIME) @Target({TYPE, METHOD}) public @interface ClusterScoped {} public @interface TransactionScoped {} public @interface ThreadScoped {} 21
  • 22. @New Qualifier • Allows to obtain a dependent object of a specified class, independent of declared scope – Useful with @Produces @ConversationScoped public class Calculator { . . . } public class PaymentCalc { @Inject Calculator calculator; @Inject @New Calculator newCalculator; } 22
  • 23. 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 23
  • 24. 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; 24
  • 25. Disposer – Sample Code @Produces @RequestScoped Connection connect(User user) { return createConnection(user.getId(), user.getPassword()); } void close(@Disposes Connection connection) { connection.close(); } 25
  • 26. 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 • 26
  • 27. 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(); } } 27
  • 28. Why Interceptor Bindings ? • Remove dependency from the interceptor implementation class • Can vary depending upon deployment environment • Allows central ordering of interceptors 28
  • 29. 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 29
  • 30. 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 30
  • 31. 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> 31
  • 32. 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> 32
  • 33. 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 33
  • 34. 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) 34
  • 35. 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” 35
  • 36. Stereotypes – Sample Code (Pre-defined) @Named @RequestScoped @Stereotype @Target({TYPE, METHOD}) @Retention(RUNTIME) public @interface Model {} • Use @Model on JSF “backing beans” 36
  • 37. Stereotypes – Sample Code (Make Your Own) @RequestScoped @Transactional(requiresNew=true) @Secure @Named @Stereotype @Retention(RUNTIME) @Target(TYPE) public @interface Action {} 37
  • 38. 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 38
  • 39. 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 39
  • 40. 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 40
  • 41. 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 41
  • 42. 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 42
  • 43. 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” 43
  • 44. 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 44
  • 45. 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 45
  • 46. 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; 46
  • 47. CDI & JPA • Create “transactional event observers” – Kinds • IN_PROGRESS • BEFORE_COMPLETION • AFTER_COMPLETION • AFTER_FAILURE • AFTER_SUCCESS – Keep the cache updated 47
  • 48. 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 48
  • 49. 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 49
  • 50. 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 50
  • 51. Portable Extension – How to author ? • Implement javax.enterprise.inject.spi.Extension SPI – Register service provider • Observe container lifecycle events – Before/AfterBeanDiscovery, ProcessAnnotatedType • Ways to integrate with container – Provide beans, interceptors, or decorators – Satisfy injection points with built-in or wrapped types – Contribute a scope and context implementation – Augment or override annotation metadata 51
  • 52. 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)); } } 52
  • 53. Portable Extensions – Weld Logger public class Checkout { @Inject Logger log; public void invoiceItems() { ShoppingCart cart; ... log.debug("Items invoiced for {}", cart); } } 53
  • 54. 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 54
  • 57. IDE Support • Inspect Observer/Producer for a given event http://wiki.netbeans.org/NewAndNoteworthyNB70#CDI 57
  • 61. 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 61
  • 62. References • glassfish.org • blogs.sun.com/theaquarium • oracle.com/goto/glassfish • youtube.com/user/GlassFishVideos • http://docs.jboss.org/weld/reference/latest/en-US/html/ • Follow @glassfish 62