SlideShare a Scribd company logo
CDI Best Practices with
Real-Life Examples
Ahmad Gohar
Software Architect & Technical Team Lead
IBM Experienced IT-Specialist
Client Innovation Center (CIC), IBM
TUT3287
Gohar , Ahmad Nabil
• Software Architect & Technical Team Lead (9Y.) | CIC, IBM.
• IBM/Open Group Certified Experienced IT Specialist.
• M.Sc. in Information System, FCI, Egypt.
• MIBA in Global Management, ESLSCA, France.
• OCEJPA | OCPWCD | OCPJP | OCP PL/SQL | MCP(s).
• JAVA Community Process (JCP) Member.
• Blogger Author and Academic Researcher.
Introduction to CDI
JSR 299: Contexts and Dependency Injection for the Java EE platform
Q : What is the old name of the CDI ?
What is CDI (JSR 299)?
• Java Specification Requests
• JSR is a document of a proposed specification used in the Java Community
Process (JCP).
• Classes specify what their dependencies
• NOT how to obtain them (container responsibility)
What is CDI (JSR 299)?
• Provides a unifying Dependency Injection and contextual life-cycle
model for Java EE
• Unified existing Dependency Injection schemes – Spring, Guice, Seam
• A completely new, richer dependency management model
• Type-safe dependency injection
• Designed for use with stateful objects (scoped objects)
What is CDI (JSR 299)?
• Makes it much easier to build applications using JSF and EJB
together
• Let you use EJBs directly as JSF managed beans
Q : What is Weld ?
What is Weld?
• The CDI Reference Implementation (RI)
• Service Provider Interfaces (SPI)
• Weld provides a complete SPI allowing Java EE containers to use
CDI implementation
• Weld also runs in servlet engines, or even in a plain Java SE
environment
Common Dependency Injection Frameworks
• Spring
• Guice
• Seam
• EJB 3.X
• CDI
CDI is more than a framework
• It’s a whole, rich programming model
• The theme of CDI is loosecoupling with strong typing.
• A bean specifies only the type and semantics of other beans it depends upon
• It need not be aware of the actual lifecycle, concrete implementation,
threading model or other clients of any bean it interacts with
• Even better, the concrete implementation, lifecycle and threading model of
a bean may vary according to the deployment scenario, without affecting
any client
• This loose-coupling makes your code easier to maintain
CDI theme – Loose coupling with Strong typing
• Events, interceptors and decorators enhance the loose-coupling
inherent in this model:
• Event notifications
• Decouple event producers from event consumers
• Interceptors
• Decouple technical concerns from business logic
• Decorators
• Allow business concerns to be compartmentalized
CDI theme – Loose coupling
• Decouple Server (dependency) and client (dependency user)
• Using well-defiend types and qualifiers
• Allows server implementations to vary
• Decouple lifecycle of collaboration components (dependencies) from
application (dependency user)
• Automatic contextual life-cycle management by the CDI runtime
• Decouple orthogonal concerns (AOP) from business logic
• Interceptors & Decorators
• Decouple message producer from consumer
• Events
CDI theme – Strong typing
• Type-based injection has advantages of
• No more reliance on string-based names
• Compiler can detect type errors at compile time
• Casting mostly eliminated
• Strong tooling possible
• Semantic code errors (errors that can't be detected by the compiler) can
be detected at application start-upon
• Tools can detect ambiguous dependencies
• Leverages Java type system
• @Annotation
• <TypeParam>
Getting our feet wet
CDI First Example
• http://ansgohar.blogspot.com/2016/09/create-first-cdi-application.html
• http://ansgohar.blogspot.com/2016/09/create-first-cdi-application.html
Automatic Bean Discovery
• • How can container scan bean?
• By detecting the presence of “beans.xml” in application archive
• For WAR file, the “beans.xml” is under WEB-INF directory
• For JAR file, the “beans.xml” is under META-INF directory
• • “beans.xml”
• It is not for declaring beans (like in Spring)
• It can be empty
• Used for some other purposes (like declaring an alternative)
Getting our feet wet
EJB Simple Example
Getting our feet wet
Injecting EJB using CDI
CDI Beans & Injection Point
CDI Beans
What is a Bean anyway?
• Many forms of a “bean” already exist. So which bean arewe talking
about?
• JSF bean
• EJB bean
• Spring bean
• Seam bean
• Guice bean
• CDI bean
• Java EE needs a unified bean definition
• Managed Bean 1.0 specification in Java EE 6 provides it
What about Managed, EJB, REST, CDI Bean?
• Managed Beans are container-managed POJOs
• Lightweight component model
• Instances are managed by the container
• You could see everything as a Managed Bean with extra services
• • An EJB is a Managed Bean with
• Transaction support
• Security
• Thread safety
• Persistence
• • A REST service is a Managed Bean with
• HTTP support
• • A CDI bean is a Managed Bean with
• CDI services (explained in the next slide)
CDI is more than a framework
• Auto-discovered
• by the container
• Set of qualifiers
• solves ambiguity
• Scope
• context of a bean
• Bean EL name
• support non-type based invocation
• Set of interceptor bindings
• Alternative
• replace bean at deployment time
CDI Beans & Injection Point
Injection Point
Managed Bean  CDI Bean
Q : How to Inject CDI Beans (Injection Point) ?
CDI Injection Point
• Use @Inject <Java-Type> <variable> for field injection
• <Java-Type> can be Java interface
• Bean can be injected at “Injection points”
• Field
• Method parameter
• Method can be
• Constructor (useful for created immutable object)
• Initializer
• Setter method
• Producer
• Observer
Injecting Interface
CDI Injection Point
CDI Injection Point
Qualifiers, Alternatives, Programmatically Lookup
Qualifiers
Q : What is the result of injecting CDI beans that :-
1- have single Implementation ?
2- have no Implementation ?
3- have multiple Implementation ?
What is a Qualifier?
• For a given bean type (class or interface), there may be multiple
beans which implement the type (in the classpath)
• For an interface, there could be multiple implementations
• For a class, there could be multiple child types
• Ambiguity error will result
• A qualifier is an annotation that lets a client choose one between
multiple candidates of a certain type
• Make type more specific
• Assigns semantic meaning
• Injected type is identified by
• Qualifier(s) + Java type
Qualifier and Type Safety (Strong Typing)
• Qualifier + Java type makes a composite type (extended type)
• Again, think of a Qualifier as a type
• Qualifiers make type safe injection possible
• Qualifiers replace “look-up via string-based names”
• Qualifier and Type Safety (Strong Typing)
Qualifiers, Alternatives, Programmatically Lookup
Alternatives
What is Alternative Bean?
• Any bean with @Alternative is not considered for injection
• Lets you package multiple beans that match injection type without ambiguity errors
• In order to be considered for injection, it has to be activated in “beans.xml”
• Provide a replacement implementation during deployment
• You can apply the @Alternative annotation to two or more beans, then, based on
your deployment, specify the bean you want to use in the “beans.xml” configuration
file
• Useful for providing mock objects for testing – mock objects are annotated with
@Alternative
Qualifiers, Alternatives, Programmatically Lookup
Programmatically Lookup
Scope, & Context
CDI Beans Scope
Q : What the allowed scopes in CDI ?
Request – @RequestScoped
• This scope describes a user’s interaction with a web
application in a single HTTP request.
• The instance of the @RequestScoped annotated
bean has an HTTP request lifecycle.
Session – @SessionScoped
• This scope describes a user’s interaction with a web
application across multiple HTTP requests.
Application – @ApplicationScoped
• In this case the state is shared across all users’
interactions with a web application.
• The container provides the same instance of the
@ApplicationScoped annotated bean to all client
requests.
Dependent – @Dependent pseudo-scope
• This pseudo-scope means that an object exists to serve
exactly one client (bean) and has the same lifecycle as
that client (bean).
• This is the default scope for a bean which does not
explicitly declare a scope type.
• An instance of a dependent bean is never shared
between different clients or different injection points.
• It is strictly a dependent object of some other object.
• It is instantiated when the object it belongs to is
created, and destroyed when the object it belongs to
is destroyed.
View – @ ViewScoped
• @ViewScoped belongs to JSF specification
• Retains the scope lifespan for current page view
• If the controller navigates away to a different page
view the bean is de-scoped
• Therefore view-scope is great for form validation
and rich AJAX request and response sequences!
Conversation – @ConversationScoped
• A lifespan sits between a Http Request scope and
Http Session scope
• Maintains state for the unique interaction
• Works for individual tab in web browsers
• Better than @ViewScoped bean controllers
• Application defined lifespan
Session & Conversation Scoped Bean
• A thing to notice is that beans must be serializable.
• This is because the container passivates the HTTP
session from time to time, so when the session is
activated again the beans’ state must be retrieved.
Singleton – @Singleton pseudo-scope
• This is a pseudo-scope.
• It defines that a bean is once instantiated.
• When a CDI managed bean is injected into another
bean, the CDI container makes use of a proxy.
• The proxy is the one to handle calls to the bean.
• Though, @Singleton annotated beans don’t have a
proxy object.
• Clients hold a direct reference to the singleton
instance.
Singleton – @Singleton pseudo-scope
• So, what happens when a client is serialized ?
• We must ensure that the singleton bean remains a
singleton.
• To do so there are a fiew ways, such as, have the
singleton bean implement writeResolve() and
readReplace() (as defined by the Java serialization
specification), make sure the client keeps only a
transient reference to the singleton bean, or give
the client a reference of type Instance<X> where X
is the bean type of the singleton bean.
Contextual scope
• All predefined scopes except @Dependent are contextual
scopes.
• CDI places beans of contextual scope in the context whose
lifecycle is defined by the Java EE specifications.
• For example, a session context and its beans exist during the
lifetime of an HTTP session.
• Injected references to the beans are contextually aware.
• The references always apply to the bean that is associated
with the context for the thread that is making the reference.
The CDI container ensures that the objects are created and
injected at the correct time as determined by the scope that
is specified for these objects.
Interceptors, & Decorators
Interceptors
Interceptors
• Interceptor functionality is defined in the Java Interceptors
specification.
• The Interceptors specification defines three kinds of interception
points:
• Business method interception,
• Lifecycle callback interception, and
• Timeout method interception (EJB only).
• A business method interceptor applies to invocations of methods
of the bean by clients of the bean
• By default, all interceptors are disabled
Business Method Interceptor
• A business method interceptor applies to invocations of methods
of the bean by clients of the bean
Lifecycle Callback Interceptor
• A lifecycle callback interceptor applies to invocations of lifecycle
callbacks by the container
• An interceptor class may intercept both lifecycle callbacks and
business methods
Timeout Method Interceptor
• A timeout method interceptor applies to invocations of EJB
timeout methods by the container
Interceptors, & Decorators
Decorators
Q : What is the deference between Interceptor and Decorators in CDI ?
What is a Decorator?
• Decorators implement the Decorator design pattern
• Allows implementation of an additional business logic for a bean
• A Decorator decorates interfaces they implement
• @Delegate is used to inject the original object
• Original object business logic can be be invoked within the decorator
• Decorators must be activated through “beans.xml”
Interceptors VS Decorators
• Interceptors and Decorators both geared towards cross-cutting
logic.
• Bypass traditional complexity associated with AOP by avoiding
point-cuts.
• Interceptors are designed for system-level crosscutting concerns
very decoupled from business logic.
• Decorators intended for concerns that should be
compartmentalized but are still very close to business logic.
Events
Events
Q : What is Events ?
CDI Event Observer Pattern
• Completely decouple action (event producer) and reactions
• (event consumers)
• Qualifiers tune which event notifications are received
• Define Event Class
• Event producer fires an event
• Event consumer observes event through @Observes
Event
• Event Producers
• An event is fired by an injected javax.enterprise.event.Event object
• Event Consumer (Event Observer)
• The only thing event consumer has to do is to use @Observes <Event-class>
annotation
CDI and EJB
When you still need EJB?
Q : When you still need EJB ?
When you still need EJB ? … not yet aligned!
• Security
• @RolesAllowed
• @PermitAll
• @DenyAll
• Usable by
• @Stateless
• @Stateful
• @Singleton
When you still need EJB ? … not yet aligned!
• Startup
• @Startup
• Eagerly creates the instance upon startup
• Usable by
• @Singleton
When you still need EJB ? … not yet aligned!
• Asynchronous
• @Asynchronsous
• Allows method calls to be asynchronous and return Future objects
• Usable by
• @Stateless
• @Stateful
• @Singleton
When you still need EJB ? … not yet aligned!
• Schedule
• @Schedule
• Effectively Cron -- schedule invocations by minute or date, etc.
• Usable by
• @Stateless
• @Singleton
• Not @Stateful
When you still need EJB ? … not yet aligned!
• Locking
• @Lock(READ
• @Lock(WRITE)
• @AccessTimeout
• Allows for synchronization of methods without complex code
• Usable by
• @Singleton
• Not @Stateless
• Not @Stateful
When you still need EJB ? … not yet aligned!
• MDBs
• @MessageDriven
• Connector-Driven Beans
• Usable by
• Not @Singleton
• Not @Stateless
• Not @Stateful
CDI Takeover
• EJB adopts CDI (Java EE 6)
• JSF adopts CDI (Java EE 7)
• MVC adopts CDI (Java EE 8)
• JAX-RS considers CDI (Java EE 8)
• CDI moves to SE (Java EE 8)
Common Mistakes you will make
• Not putting a beans.xml in your app (Java EE 6)
• No CDI for you!
• Not understanding @Typed
• Think @Local from EJB
• Bites you when using @Produces
• Not understanding what Dependent and NormalScope
• Dependent == plain object
• NormalScoped == proxied object
• Bites you when creating custom scopes
Result for EJB after CDI ?
• Java EE 7
• Focus on realignment: @Transactional
• • Java EE 8
• First spec round with no new EJB JSR
• Realignment stalled
• Awkward relationship
CDI Wrap-up
Who did this now ! ! !
CDI Wrap-up
• Basic dependency injection
• @Inject, @Qualifier, @Stereotype, @Alternative,
• Instance, @All, @Any
• Component naming
• @Named
• Context management
• @Dependent, @RequestScoped, @SessionScoped,
• @ConversationScoped, @ApplicationScoped,
• @Scope
CDI Wrapup
• Custom Object Factories
• @Produces, @Disposes, InjectionPoint
• Lightweight Events
• Event, @Observes
• Interceptors/Decorators
• @Interceptor, @InterceptorBinding, @AroundInvoke,
• InvocationContext
• @Decorator, @Delegate
Biggest benefits of CDI
• Very active and open expert group
• Fully extendable
• Beans can be added at runtime
• Fully Open Source
• Spec is open source
• All implementations are open source
• Compliance test (TCK) suite is open source
Q & A
•https://about.me/ansgohar
•http://ansgohar.blogspot.co.uk
•https://twitter.com/ansgohar
CDI Best Practices with Real-Life Examples - TUT3287

More Related Content

What's hot

Presentation on the Provisions of CAG's (DPC) Act, 1971
Presentation on the Provisions of CAG's (DPC) Act, 1971Presentation on the Provisions of CAG's (DPC) Act, 1971
Presentation on the Provisions of CAG's (DPC) Act, 1971
Life of A Public Auditor
 
Law of the Sea.pptx
Law of the Sea.pptxLaw of the Sea.pptx
Law of the Sea.pptx
Dr. Asser Harb
 
Economically Weaker Sections(EWS)
Economically Weaker Sections(EWS)Economically Weaker Sections(EWS)
Economically Weaker Sections(EWS)
bansi default
 
LABOUR LAW - II
LABOUR LAW - IILABOUR LAW - II
LABOUR LAW - II
cpjcollege
 
Top 10 law professor interview questions and answers
Top 10 law professor interview questions and answersTop 10 law professor interview questions and answers
Top 10 law professor interview questions and answers
jessicacindy3
 
Kerala Government Office Manual- How to inspect personal registers- uploaded ...
Kerala Government Office Manual- How to inspect personal registers- uploaded ...Kerala Government Office Manual- How to inspect personal registers- uploaded ...
Kerala Government Office Manual- How to inspect personal registers- uploaded ...
Jamesadhikaram land matter consultancy 9447464502
 
The Gujarat Victim Compensation Scheme, 2016
The Gujarat Victim Compensation Scheme, 2016The Gujarat Victim Compensation Scheme, 2016
The Gujarat Victim Compensation Scheme, 2016
Legal
 
Taxation Law
Taxation LawTaxation Law
Taxation Law
cpjcollege
 
Human rights unit 5
Human rights unit 5Human rights unit 5
Human rights unit 5
Nagasudhakar Akula
 
Juvenile Justice Act - Classification of Offences under the JJ Act
Juvenile Justice Act -  Classification of Offences under the JJ ActJuvenile Justice Act -  Classification of Offences under the JJ Act
Juvenile Justice Act - Classification of Offences under the JJ Act
Legal
 
Eviction under tamilnadu rent control act
Eviction under tamilnadu rent control actEviction under tamilnadu rent control act
Eviction under tamilnadu rent control actAltacit Global
 
General financial rules
General financial rulesGeneral financial rules
General financial rules
aagkingshuk
 
Place of suing
Place of suingPlace of suing
Place of suing
Neepa Jani Vyas
 
Tax Law (LLB-403)
Tax Law (LLB-403)Tax Law (LLB-403)
Tax Law (LLB-403)
cpjcollege
 
Optional registration of documents under the registration act, 1908
Optional registration of documents under the registration act, 1908Optional registration of documents under the registration act, 1908
Optional registration of documents under the registration act, 1908
IshaKhalid3
 
Income from house property
Income from house propertyIncome from house property
Income from house property
Kshitij Gupta
 
Concept of residence under income tax act (with the concept of dtaa and poem)
Concept of residence under income tax act (with the concept of dtaa and poem)Concept of residence under income tax act (with the concept of dtaa and poem)
Concept of residence under income tax act (with the concept of dtaa and poem)
Amitabh Srivastava
 

What's hot (20)

Presentation on the Provisions of CAG's (DPC) Act, 1971
Presentation on the Provisions of CAG's (DPC) Act, 1971Presentation on the Provisions of CAG's (DPC) Act, 1971
Presentation on the Provisions of CAG's (DPC) Act, 1971
 
Law of the Sea.pptx
Law of the Sea.pptxLaw of the Sea.pptx
Law of the Sea.pptx
 
Economically Weaker Sections(EWS)
Economically Weaker Sections(EWS)Economically Weaker Sections(EWS)
Economically Weaker Sections(EWS)
 
LABOUR LAW - II
LABOUR LAW - IILABOUR LAW - II
LABOUR LAW - II
 
Top 10 law professor interview questions and answers
Top 10 law professor interview questions and answersTop 10 law professor interview questions and answers
Top 10 law professor interview questions and answers
 
Kerala Government Office Manual- How to inspect personal registers- uploaded ...
Kerala Government Office Manual- How to inspect personal registers- uploaded ...Kerala Government Office Manual- How to inspect personal registers- uploaded ...
Kerala Government Office Manual- How to inspect personal registers- uploaded ...
 
The Gujarat Victim Compensation Scheme, 2016
The Gujarat Victim Compensation Scheme, 2016The Gujarat Victim Compensation Scheme, 2016
The Gujarat Victim Compensation Scheme, 2016
 
Taxation Law
Taxation LawTaxation Law
Taxation Law
 
Human rights unit 5
Human rights unit 5Human rights unit 5
Human rights unit 5
 
Advance pricing agreement
Advance pricing agreementAdvance pricing agreement
Advance pricing agreement
 
Indian registration act 1908.bose
Indian registration act 1908.boseIndian registration act 1908.bose
Indian registration act 1908.bose
 
Juvenile Justice Act - Classification of Offences under the JJ Act
Juvenile Justice Act -  Classification of Offences under the JJ ActJuvenile Justice Act -  Classification of Offences under the JJ Act
Juvenile Justice Act - Classification of Offences under the JJ Act
 
Eviction under tamilnadu rent control act
Eviction under tamilnadu rent control actEviction under tamilnadu rent control act
Eviction under tamilnadu rent control act
 
General financial rules
General financial rulesGeneral financial rules
General financial rules
 
Place of suing
Place of suingPlace of suing
Place of suing
 
Tax Law (LLB-403)
Tax Law (LLB-403)Tax Law (LLB-403)
Tax Law (LLB-403)
 
KBT
KBTKBT
KBT
 
Optional registration of documents under the registration act, 1908
Optional registration of documents under the registration act, 1908Optional registration of documents under the registration act, 1908
Optional registration of documents under the registration act, 1908
 
Income from house property
Income from house propertyIncome from house property
Income from house property
 
Concept of residence under income tax act (with the concept of dtaa and poem)
Concept of residence under income tax act (with the concept of dtaa and poem)Concept of residence under income tax act (with the concept of dtaa and poem)
Concept of residence under income tax act (with the concept of dtaa and poem)
 

Similar to CDI Best Practices with Real-Life Examples - TUT3287

Spring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreSpring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-Core
Donald Lika
 
The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...
Paul Bakker
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI Interop
Ray Ploski
 
Spring introduction
Spring introductionSpring introduction
Spring introductionLê Hảo
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
BruceLee275640
 
Java online training from hyderabad
Java online training from hyderabadJava online training from hyderabad
Java online training from hyderabad
revanthonline
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
Vibrant Technologies & Computers
 
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
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformBozhidar Bozhanov
 
Gwt cdi jud_con_berlin
Gwt cdi jud_con_berlinGwt cdi jud_con_berlin
Gwt cdi jud_con_berlin
hbraun
 
MyFaces CODI Conversations
MyFaces CODI ConversationsMyFaces CODI Conversations
MyFaces CODI Conversations
os890
 
Designing your API Server for mobile apps
Designing your API Server for mobile appsDesigning your API Server for mobile apps
Designing your API Server for mobile appsMugunth Kumar
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
Kongu Engineering College, Perundurai, Erode
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans Technology
Simon Ritter
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to SpringSujit Kumar
 
Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Rohit Kelapure
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
PawanMM
 

Similar to CDI Best Practices with Real-Life Examples - TUT3287 (20)

Spring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreSpring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-Core
 
The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...The future of enterprise dependency injection: Contexts & Dependency Injectio...
The future of enterprise dependency injection: Contexts & Dependency Injectio...
 
Spring - CDI Interop
Spring - CDI InteropSpring - CDI Interop
Spring - CDI Interop
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 
Java online training from hyderabad
Java online training from hyderabadJava online training from hyderabad
Java online training from hyderabad
 
Unit4wt
Unit4wtUnit4wt
Unit4wt
 
Unit4wt
Unit4wtUnit4wt
Unit4wt
 
Hybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbaiHybernat and structs, spring classes in mumbai
Hybernat and structs, spring classes in mumbai
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
 
Contexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platformContexts and Dependency Injection for the JavaEE platform
Contexts and Dependency Injection for the JavaEE platform
 
Gwt cdi jud_con_berlin
Gwt cdi jud_con_berlinGwt cdi jud_con_berlin
Gwt cdi jud_con_berlin
 
MyFaces CODI Conversations
MyFaces CODI ConversationsMyFaces CODI Conversations
MyFaces CODI Conversations
 
Designing your API Server for mobile apps
Designing your API Server for mobile appsDesigning your API Server for mobile apps
Designing your API Server for mobile apps
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Introduction to Spring & Spring BootFramework
Introduction to Spring  & Spring BootFrameworkIntroduction to Spring  & Spring BootFramework
Introduction to Spring & Spring BootFramework
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans Technology
 
Introduction to Spring
Introduction to SpringIntroduction to Spring
Introduction to Spring
 
Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010
 
Session 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI BeansSession 43 - Spring - Part 1 - IoC DI Beans
Session 43 - Spring - Part 1 - IoC DI Beans
 

Recently uploaded

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 

Recently uploaded (20)

How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 

CDI Best Practices with Real-Life Examples - TUT3287

  • 1. CDI Best Practices with Real-Life Examples Ahmad Gohar Software Architect & Technical Team Lead IBM Experienced IT-Specialist Client Innovation Center (CIC), IBM TUT3287
  • 2.
  • 3. Gohar , Ahmad Nabil • Software Architect & Technical Team Lead (9Y.) | CIC, IBM. • IBM/Open Group Certified Experienced IT Specialist. • M.Sc. in Information System, FCI, Egypt. • MIBA in Global Management, ESLSCA, France. • OCEJPA | OCPWCD | OCPJP | OCP PL/SQL | MCP(s). • JAVA Community Process (JCP) Member. • Blogger Author and Academic Researcher.
  • 4.
  • 5.
  • 6. Introduction to CDI JSR 299: Contexts and Dependency Injection for the Java EE platform
  • 7. Q : What is the old name of the CDI ?
  • 8. What is CDI (JSR 299)? • Java Specification Requests • JSR is a document of a proposed specification used in the Java Community Process (JCP). • Classes specify what their dependencies • NOT how to obtain them (container responsibility)
  • 9. What is CDI (JSR 299)? • Provides a unifying Dependency Injection and contextual life-cycle model for Java EE • Unified existing Dependency Injection schemes – Spring, Guice, Seam • A completely new, richer dependency management model • Type-safe dependency injection • Designed for use with stateful objects (scoped objects)
  • 10. What is CDI (JSR 299)? • Makes it much easier to build applications using JSF and EJB together • Let you use EJBs directly as JSF managed beans
  • 11. Q : What is Weld ?
  • 12. What is Weld? • The CDI Reference Implementation (RI) • Service Provider Interfaces (SPI) • Weld provides a complete SPI allowing Java EE containers to use CDI implementation • Weld also runs in servlet engines, or even in a plain Java SE environment
  • 13. Common Dependency Injection Frameworks • Spring • Guice • Seam • EJB 3.X • CDI
  • 14. CDI is more than a framework • It’s a whole, rich programming model • The theme of CDI is loosecoupling with strong typing. • A bean specifies only the type and semantics of other beans it depends upon • It need not be aware of the actual lifecycle, concrete implementation, threading model or other clients of any bean it interacts with • Even better, the concrete implementation, lifecycle and threading model of a bean may vary according to the deployment scenario, without affecting any client • This loose-coupling makes your code easier to maintain
  • 15. CDI theme – Loose coupling with Strong typing • Events, interceptors and decorators enhance the loose-coupling inherent in this model: • Event notifications • Decouple event producers from event consumers • Interceptors • Decouple technical concerns from business logic • Decorators • Allow business concerns to be compartmentalized
  • 16. CDI theme – Loose coupling • Decouple Server (dependency) and client (dependency user) • Using well-defiend types and qualifiers • Allows server implementations to vary • Decouple lifecycle of collaboration components (dependencies) from application (dependency user) • Automatic contextual life-cycle management by the CDI runtime • Decouple orthogonal concerns (AOP) from business logic • Interceptors & Decorators • Decouple message producer from consumer • Events
  • 17. CDI theme – Strong typing • Type-based injection has advantages of • No more reliance on string-based names • Compiler can detect type errors at compile time • Casting mostly eliminated • Strong tooling possible • Semantic code errors (errors that can't be detected by the compiler) can be detected at application start-upon • Tools can detect ambiguous dependencies • Leverages Java type system • @Annotation • <TypeParam>
  • 18. Getting our feet wet CDI First Example
  • 21. Automatic Bean Discovery • • How can container scan bean? • By detecting the presence of “beans.xml” in application archive • For WAR file, the “beans.xml” is under WEB-INF directory • For JAR file, the “beans.xml” is under META-INF directory • • “beans.xml” • It is not for declaring beans (like in Spring) • It can be empty • Used for some other purposes (like declaring an alternative)
  • 22. Getting our feet wet EJB Simple Example
  • 23.
  • 24. Getting our feet wet Injecting EJB using CDI
  • 25.
  • 26. CDI Beans & Injection Point CDI Beans
  • 27. What is a Bean anyway? • Many forms of a “bean” already exist. So which bean arewe talking about? • JSF bean • EJB bean • Spring bean • Seam bean • Guice bean • CDI bean • Java EE needs a unified bean definition • Managed Bean 1.0 specification in Java EE 6 provides it
  • 28. What about Managed, EJB, REST, CDI Bean? • Managed Beans are container-managed POJOs • Lightweight component model • Instances are managed by the container • You could see everything as a Managed Bean with extra services • • An EJB is a Managed Bean with • Transaction support • Security • Thread safety • Persistence • • A REST service is a Managed Bean with • HTTP support • • A CDI bean is a Managed Bean with • CDI services (explained in the next slide)
  • 29. CDI is more than a framework • Auto-discovered • by the container • Set of qualifiers • solves ambiguity • Scope • context of a bean • Bean EL name • support non-type based invocation • Set of interceptor bindings • Alternative • replace bean at deployment time
  • 30. CDI Beans & Injection Point Injection Point
  • 31. Managed Bean  CDI Bean
  • 32. Q : How to Inject CDI Beans (Injection Point) ?
  • 33. CDI Injection Point • Use @Inject <Java-Type> <variable> for field injection • <Java-Type> can be Java interface • Bean can be injected at “Injection points” • Field • Method parameter • Method can be • Constructor (useful for created immutable object) • Initializer • Setter method • Producer • Observer
  • 38. Q : What is the result of injecting CDI beans that :- 1- have single Implementation ? 2- have no Implementation ? 3- have multiple Implementation ?
  • 39. What is a Qualifier? • For a given bean type (class or interface), there may be multiple beans which implement the type (in the classpath) • For an interface, there could be multiple implementations • For a class, there could be multiple child types • Ambiguity error will result • A qualifier is an annotation that lets a client choose one between multiple candidates of a certain type • Make type more specific • Assigns semantic meaning • Injected type is identified by • Qualifier(s) + Java type
  • 40.
  • 41.
  • 42.
  • 43. Qualifier and Type Safety (Strong Typing) • Qualifier + Java type makes a composite type (extended type) • Again, think of a Qualifier as a type • Qualifiers make type safe injection possible • Qualifiers replace “look-up via string-based names” • Qualifier and Type Safety (Strong Typing)
  • 45. What is Alternative Bean? • Any bean with @Alternative is not considered for injection • Lets you package multiple beans that match injection type without ambiguity errors • In order to be considered for injection, it has to be activated in “beans.xml” • Provide a replacement implementation during deployment • You can apply the @Alternative annotation to two or more beans, then, based on your deployment, specify the bean you want to use in the “beans.xml” configuration file • Useful for providing mock objects for testing – mock objects are annotated with @Alternative
  • 46.
  • 47. Qualifiers, Alternatives, Programmatically Lookup Programmatically Lookup
  • 48.
  • 49. Scope, & Context CDI Beans Scope
  • 50. Q : What the allowed scopes in CDI ?
  • 51. Request – @RequestScoped • This scope describes a user’s interaction with a web application in a single HTTP request. • The instance of the @RequestScoped annotated bean has an HTTP request lifecycle.
  • 52. Session – @SessionScoped • This scope describes a user’s interaction with a web application across multiple HTTP requests.
  • 53. Application – @ApplicationScoped • In this case the state is shared across all users’ interactions with a web application. • The container provides the same instance of the @ApplicationScoped annotated bean to all client requests.
  • 54. Dependent – @Dependent pseudo-scope • This pseudo-scope means that an object exists to serve exactly one client (bean) and has the same lifecycle as that client (bean). • This is the default scope for a bean which does not explicitly declare a scope type. • An instance of a dependent bean is never shared between different clients or different injection points. • It is strictly a dependent object of some other object. • It is instantiated when the object it belongs to is created, and destroyed when the object it belongs to is destroyed.
  • 55.
  • 56.
  • 57. View – @ ViewScoped • @ViewScoped belongs to JSF specification • Retains the scope lifespan for current page view • If the controller navigates away to a different page view the bean is de-scoped • Therefore view-scope is great for form validation and rich AJAX request and response sequences!
  • 58. Conversation – @ConversationScoped • A lifespan sits between a Http Request scope and Http Session scope • Maintains state for the unique interaction • Works for individual tab in web browsers • Better than @ViewScoped bean controllers • Application defined lifespan
  • 59.
  • 60. Session & Conversation Scoped Bean • A thing to notice is that beans must be serializable. • This is because the container passivates the HTTP session from time to time, so when the session is activated again the beans’ state must be retrieved.
  • 61. Singleton – @Singleton pseudo-scope • This is a pseudo-scope. • It defines that a bean is once instantiated. • When a CDI managed bean is injected into another bean, the CDI container makes use of a proxy. • The proxy is the one to handle calls to the bean. • Though, @Singleton annotated beans don’t have a proxy object. • Clients hold a direct reference to the singleton instance.
  • 62. Singleton – @Singleton pseudo-scope • So, what happens when a client is serialized ? • We must ensure that the singleton bean remains a singleton. • To do so there are a fiew ways, such as, have the singleton bean implement writeResolve() and readReplace() (as defined by the Java serialization specification), make sure the client keeps only a transient reference to the singleton bean, or give the client a reference of type Instance<X> where X is the bean type of the singleton bean.
  • 63. Contextual scope • All predefined scopes except @Dependent are contextual scopes. • CDI places beans of contextual scope in the context whose lifecycle is defined by the Java EE specifications. • For example, a session context and its beans exist during the lifetime of an HTTP session. • Injected references to the beans are contextually aware. • The references always apply to the bean that is associated with the context for the thread that is making the reference. The CDI container ensures that the objects are created and injected at the correct time as determined by the scope that is specified for these objects.
  • 64.
  • 66. Interceptors • Interceptor functionality is defined in the Java Interceptors specification. • The Interceptors specification defines three kinds of interception points: • Business method interception, • Lifecycle callback interception, and • Timeout method interception (EJB only). • A business method interceptor applies to invocations of methods of the bean by clients of the bean • By default, all interceptors are disabled
  • 67. Business Method Interceptor • A business method interceptor applies to invocations of methods of the bean by clients of the bean
  • 68. Lifecycle Callback Interceptor • A lifecycle callback interceptor applies to invocations of lifecycle callbacks by the container • An interceptor class may intercept both lifecycle callbacks and business methods
  • 69. Timeout Method Interceptor • A timeout method interceptor applies to invocations of EJB timeout methods by the container
  • 70.
  • 72. Q : What is the deference between Interceptor and Decorators in CDI ?
  • 73. What is a Decorator? • Decorators implement the Decorator design pattern • Allows implementation of an additional business logic for a bean • A Decorator decorates interfaces they implement • @Delegate is used to inject the original object • Original object business logic can be be invoked within the decorator • Decorators must be activated through “beans.xml”
  • 74.
  • 75.
  • 76. Interceptors VS Decorators • Interceptors and Decorators both geared towards cross-cutting logic. • Bypass traditional complexity associated with AOP by avoiding point-cuts. • Interceptors are designed for system-level crosscutting concerns very decoupled from business logic. • Decorators intended for concerns that should be compartmentalized but are still very close to business logic.
  • 78. Q : What is Events ?
  • 79. CDI Event Observer Pattern • Completely decouple action (event producer) and reactions • (event consumers) • Qualifiers tune which event notifications are received • Define Event Class • Event producer fires an event • Event consumer observes event through @Observes
  • 80. Event • Event Producers • An event is fired by an injected javax.enterprise.event.Event object • Event Consumer (Event Observer) • The only thing event consumer has to do is to use @Observes <Event-class> annotation
  • 81.
  • 82. CDI and EJB When you still need EJB?
  • 83. Q : When you still need EJB ?
  • 84. When you still need EJB ? … not yet aligned! • Security • @RolesAllowed • @PermitAll • @DenyAll • Usable by • @Stateless • @Stateful • @Singleton
  • 85. When you still need EJB ? … not yet aligned! • Startup • @Startup • Eagerly creates the instance upon startup • Usable by • @Singleton
  • 86. When you still need EJB ? … not yet aligned! • Asynchronous • @Asynchronsous • Allows method calls to be asynchronous and return Future objects • Usable by • @Stateless • @Stateful • @Singleton
  • 87. When you still need EJB ? … not yet aligned! • Schedule • @Schedule • Effectively Cron -- schedule invocations by minute or date, etc. • Usable by • @Stateless • @Singleton • Not @Stateful
  • 88. When you still need EJB ? … not yet aligned! • Locking • @Lock(READ • @Lock(WRITE) • @AccessTimeout • Allows for synchronization of methods without complex code • Usable by • @Singleton • Not @Stateless • Not @Stateful
  • 89. When you still need EJB ? … not yet aligned! • MDBs • @MessageDriven • Connector-Driven Beans • Usable by • Not @Singleton • Not @Stateless • Not @Stateful
  • 90. CDI Takeover • EJB adopts CDI (Java EE 6) • JSF adopts CDI (Java EE 7) • MVC adopts CDI (Java EE 8) • JAX-RS considers CDI (Java EE 8) • CDI moves to SE (Java EE 8)
  • 91. Common Mistakes you will make • Not putting a beans.xml in your app (Java EE 6) • No CDI for you! • Not understanding @Typed • Think @Local from EJB • Bites you when using @Produces • Not understanding what Dependent and NormalScope • Dependent == plain object • NormalScoped == proxied object • Bites you when creating custom scopes
  • 92. Result for EJB after CDI ? • Java EE 7 • Focus on realignment: @Transactional • • Java EE 8 • First spec round with no new EJB JSR • Realignment stalled • Awkward relationship
  • 93. CDI Wrap-up Who did this now ! ! !
  • 94. CDI Wrap-up • Basic dependency injection • @Inject, @Qualifier, @Stereotype, @Alternative, • Instance, @All, @Any • Component naming • @Named • Context management • @Dependent, @RequestScoped, @SessionScoped, • @ConversationScoped, @ApplicationScoped, • @Scope
  • 95. CDI Wrapup • Custom Object Factories • @Produces, @Disposes, InjectionPoint • Lightweight Events • Event, @Observes • Interceptors/Decorators • @Interceptor, @InterceptorBinding, @AroundInvoke, • InvocationContext • @Decorator, @Delegate
  • 96. Biggest benefits of CDI • Very active and open expert group • Fully extendable • Beans can be added at runtime • Fully Open Source • Spec is open source • All implementations are open source • Compliance test (TCK) suite is open source