Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Exploring the power of CDI in 50 minutes

Exploring the power of CDI in 50 minutes

My Session at Java2Days 2016 @ Sofia, Bulgaria

http://2016.java2days.com/agenda/

Ahmad Gohar

November 17, 2016
Tweet

More Decks by Ahmad Gohar

Other Decks in Programming

Transcript

  1. EXPLORING THE POWER OF CDI
    IN 50 MINUTES
    AHMAD GOHAR
    SOFTWARE ARCHITECT & TECHNICAL TEAM LEAD, IBM
    Java2Days

    View Slide

  2. GOHAR , AHMAD NABIL
    • Software Architect & Technical Team Lead (9Y.) | CIC, IBM.
    • Duke Award Winner 2016.
    • 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.

    View Slide

  3. View Slide

  4. View Slide

  5. INTRODUCTION TO CDI
    JSR 299: Contexts and Dependency Injection for the Java EE platform

    View Slide

  6. Q : What is the old name of the CDI ?

    View Slide

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

    View Slide

  8. COMMON DEPENDENCY INJECTION FRAMEWORKS
    • Spring
    • Guice
    • Seam
    • EJB 3.X
    • CDI

    View Slide

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

    View Slide

  10. GETTING OUR FEET WET
    CDI First Example

    View Slide

  11. • http://ansgohar.blogspot.com/2016/09/create-first-cdi-application.html

    View Slide

  12. • http://ansgohar.blogspot.com/2016/09/create-first-cdi-application.html

    View Slide

  13. 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)

    View Slide

  14. GETTING OUR FEET WET
    EJB Simple Example

    View Slide

  15. View Slide

  16. GETTING OUR FEET WET
    Injecting EJB using CDI

    View Slide

  17. View Slide

  18. CDI BEANS & INJECTION POINT
    CDI Beans

    View Slide

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

    View Slide

  20. 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)

    View Slide

  21. CDI BEANS & INJECTION POINT
    Injection Point

    View Slide

  22. MANAGED BEAN  CDI BEAN

    View Slide

  23. Q : How to Inject CDI Beans (Injection Point) ?

    View Slide

  24. CDI INJECTION POINT
    • Use @Inject for field injection
    • 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

    View Slide

  25. INJECTING INTERFACE

    View Slide

  26. CDI INJECTION POINT

    View Slide

  27. CDI INJECTION POINT

    View Slide

  28. QUALIFIERS, ALTERNATIVES, PROGRAMMATICALLY LOOKUP
    Qualifiers

    View Slide

  29. Q : What is the result of injecting CDI beans that :-
    1- have single Implementation ?
    2- have no Implementation ?
    3- have multiple Implementation ?

    View Slide

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

    View Slide

  31. View Slide

  32. View Slide

  33. View Slide

  34. View Slide

  35. 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)

    View Slide

  36. Q : - How to provide a replacement implementation during deployment?

    View Slide

  37. QUALIFIERS, ALTERNATIVES, PROGRAMMATICALLY LOOKUP
    Alternatives

    View Slide

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

    View Slide

  39. View Slide

  40. Q : - How to provide a replacement implementation during runtime?

    View Slide

  41. QUALIFIERS, ALTERNATIVES, PROGRAMMATICALLY LOOKUP
    Programmatically Lookup

    View Slide

  42. View Slide

  43. SCOPE, & CONTEXT
    CDI Beans Scope

    View Slide

  44. Q : What the allowed scopes in CDI ?

    View Slide

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

    View Slide

  46. SESSION – @SESSIONSCOPED
    • This scope describes a user’s interaction with a web
    application across multiple HTTP requests.

    View Slide

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

    View Slide

  48. 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 Slide

  49. View Slide

  50. View Slide

  51. 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!

    View Slide

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

    View Slide

  53. View Slide

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

    View Slide

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

    View Slide

  56. 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 where X is the bean type of the singleton
    bean.

    View Slide

  57. CONTEXTUAL SCOPE

    View Slide

  58. INTERCEPTORS, & DECORATORS
    Interceptors

    View Slide

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

    View Slide

  60. BUSINESS METHOD INTERCEPTOR
    • A business method interceptor applies to invocations of methods of the bean by clients of
    the bean

    View Slide

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

    View Slide

  62. TIMEOUT METHOD INTERCEPTOR
    • A timeout method interceptor applies to invocations of EJB timeout methods by the
    container

    View Slide

  63. View Slide

  64. INTERCEPTORS, & DECORATORS
    Decorators

    View Slide

  65. 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”

    View Slide

  66. View Slide

  67. View Slide

  68. Q : What is the deference between Interceptor and Decorators in CDI ?

    View Slide

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

    View Slide

  70. EVENTS
    Events

    View Slide

  71. Q : What is Events ?

    View Slide

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

    View Slide

  73. 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 annotation

    View Slide

  74. View Slide

  75. CDI AND EJB
    When you still need EJB?

    View Slide

  76. Q : When you still need EJB ?

    View Slide

  77. WHEN YOU STILL NEED EJB ? … NOT YET ALIGNED!
    • Security
    • @RolesAllowed
    • @PermitAll
    • @DenyAll
    • Usable by
    • @Stateless
    • @Stateful
    • @Singleton

    View Slide

  78. WHEN YOU STILL NEED EJB ? … NOT YET ALIGNED!
    • Startup
    • @Startup
    • Eagerly creates the instance upon startup
    • Usable by
    • @Singleton

    View Slide

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

    View Slide

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

    View Slide

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

    View Slide

  82. WHEN YOU STILL NEED EJB ? … NOT YET ALIGNED!
    • MDBs
    • @MessageDriven
    • Connector-Driven Beans
    • Usable by
    • Not @Singleton
    • Not @Stateless
    • Not @Stateful

    View Slide

  83. 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)

    View Slide

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

    View Slide

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

    View Slide

  86. CDI WRAP-UP
    Who did this now ! ! !

    View Slide

  87. CDI WRAP-UP
    • Basic dependency injection
    • @Inject, @Qualifier, @Alternative,
    • Instance, @All, @Any
    • Component naming
    • @Named
    • Context management
    • @Dependent, @RequestScoped, @SessionScoped, @ConversationScoped,
    @ApplicationScoped, @Scope

    View Slide

  88. CDI WRAP-UP
    • Custom Object Factories
    • @Produces, @Disposes, InjectionPoint
    • Lightweight Events
    • @Event, @Observes
    • Interceptors/Decorators
    • @Interceptor, @InterceptorBinding, @AroundInvoke,
    • InvocationContext
    • @Decorator, @Delegate

    View Slide

  89. BIGGEST BENEFITS OF CDI
    • Very active and open expert group
    • Fully extendable
    • Beans can be added at development, deployment, or even runtime
    • Fully Open Source
    • Spec is open source
    • All implementations are open source
    • Compliance test (TCK) suite is open source

    View Slide

  90. Q & A
    •https://about.me/ansgohar
    •http://ansgohar.blogspot.co.uk
    •https://twitter.com/ansgohar

    View Slide

  91. View Slide