Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

1/3 : introduction to CDI - Antoine Sabot-Durand

1,069 views

Published on

Allez plus Loin avec CDI

En moins de 5 ans d’existence, Contexts and Dependency Injection (CDI) est devenue l’une des principale spécification de Java EE. Néanmoins, CDI est bien souvent perçu comme une simple solution d’injection de dépendance enrichie alors que cette spécification est bien plus riche que ça. Lors de cette présentation, après un rapide rappel des fonctionnalités de base de CDI, nous montrerons comment son utilisation avancée permet Java EE en intégrant des technologies legacy ou plus récent de manière naturelle. Nous finirons avec le travail en cours sur CDI 2.0 qui a commencé début septembre.

Published in: Technology
  • Be the first to comment

1/3 : introduction to CDI - Antoine Sabot-Durand

  1. 1. INTRODUCTION TO CONTEXTS AND DEPENDENCY INJECTION (CDI) @antoine_sd
  2. 2. ANTOINE SABOT-DURAND • Senior Software Engineer @Red Hat • Java & OSS : • CDI co-spec lead • CDI community development • Tech Lead on Agorava • @antoine_sd
  3. 3. WHAT IS CDI ? • Java EE dependency injection standard • Strong typed and type safe • Context management • Observer pattern included (Event bus) • Highly extensible
  4. 4. Previously on CDI
  5. 5. A BIT OF HISTORY CDI 1.0 (Java EE 6) CDI 1.1 (Java EE 7) CDI 1.2 (1.1 MR) CDI 2.0 Starts Dec 2009 June 2013 Apr 2014 Sep 2014 CDI 2.0 released Q1 2016
  6. 6. IMPLEMENTATIONS JBoss Weld (Reference Implementation) Apache Open WebBeans
  7. 7. CDI ACTIVATION • In CDI 1.0, you must add a beans.xml file to your archive • Since CDI 1.1, it’s activated by default: • All classes having a “bean defining annotation” become a bean • You can still use beans.xml file to activate CDI explicitly or deactivate it
  8. 8. THE CDI BEAN • In Java EE 6 and 7 everything is a Managed Bean • Managed beans are basic components • They are managed by the container • They all have a lifecycle • They can be intercepted (AOP) • They can be injected • Accessible from outside CDI code.
  9. 9. BASIC DEPENDENCY INJECTION @Inject
  10. 10. THIS IS A BEAN public class HelloService { public String hello() { return "Hello World!"; } }
  11. 11. DI IN CONSTRUCTOR public class MyBean { private HelloService service; @Inject public MyBean(HelloService service) { this.service = service; } }
  12. 12. DI IN SETTER public class MyBean { private HelloService service; @Inject public void setService(HelloService service) { this.service = service; } }
  13. 13. DI IN FIELD public class MyBean { @Inject private HelloService service; public void displayHello() { display(service.hello(); } }
  14. 14. NO TYPE ERASURE IN CDI public class MyBean { @Inject Service<User> userService; @Inject Service<Staff> staffService; }
  15. 15. NO TYPE ERASURE IN CDI public class MyBean { @Inject Service<User> userService; @Inject Service<Staff> staffService; } This works
  16. 16. USING QUALIFIERS TO DISTINGUISH BEANS OF THE SAME TYPE
  17. 17. 2 SERVICE IMPLEMENTATIONS… public interface HelloService { public String hello(); } public class FrenchHelloService implements HelloService { public String hello() { return "Bonjour tout le monde!"; } } public class EnglishHelloService implements HelloService { public String hello() { return "Hello World!"; } }
  18. 18. …NEED QUALIFIERS… @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface French {} @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface English {}
  19. 19. …TO BE DISTINGUISHED. @French public class FrenchHelloService implements HelloService { public String hello() { return "Bonjour tout le monde!"; } } @English public class EnglishHelloService implements HelloService { public String hello() { return "Hello World!"; } }
  20. 20. QUALIFIED INJECTION POINTS public class MyBean { @Inject @French HelloService service; public void displayHello() { display( service.hello(); } } public class MyBean { @Inject @English HelloService service; public void displayHello() { display( service.hello(); } }
  21. 21. QUALIFIERS CAN HAVE MEMBERS @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface Language { Languages value(); @Nonbinding String description() default ""; public enum Languages { FRENCH, ENGLISH } }
  22. 22. QUALIFIERS WITH MEMBERS 1/2 @Language(FRENCH) public class FrenchHelloService implements HelloService { public String hello() { return "Bonjour tout le monde!"; } } @Language(ENGLISH) public class EnglishHelloService implements HelloService { public String hello() { return "Hello World!"; } }
  23. 23. QUALIFIERS WITH MEMBERS 2/2 public class MyBean { @Inject @Language(ENGLISH) HelloService service; public void displayHello() { display( service.hello(); } } public class MyBean { @Inject @Language(FRENCH) HelloService service; public void displayHello() { display( service.hello(); } }
  24. 24. MULTIPLE QUALIFIERS public class MyBean { @Inject @French HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  25. 25. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  26. 26. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console @Secured HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  27. 27. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console @Secured HelloService service; } @French @Secured public class FrenchHelloService implements HelloService { }
  28. 28. MULTIPLE QUALIFIERS public class MyBean { @Inject @French @Console @Secured HelloService service; } @French @Secured public class FrenchHelloService implements HelloService { }
  29. 29. RESERVED QUALIFIERS @Default @Any @Named
  30. 30. PROGRAMMATIC LOOKUP
  31. 31. SOMETIMES CALLED “LAZY INJECTION” public class MyBean { @Inject Instance<HelloService> service; public void displayHello() { display( service.get().hello() ); } }
  32. 32. CHECK BEAN EXISTENCE AT RUNTIME public class MyBean { @Inject Instance<HelloService> service; public void displayHello() { if (!service.isUnsatisfied()) { display( service.get().hello() ); } } }
  33. 33. INSTANCE<T> IS ITERABLE public interface Instance<T> extends Iterable<T>, Provider<T> { public Instance<T> select(Annotation... qualifiers); public <U extends T> Instance<U> select(Class<U> subtype, Annotation... qualifiers); public <U extends T> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers); public boolean isUnsatisfied(); public boolean isAmbiguous(); public void destroy(T instance); }
  34. 34. LOOP ON ALL BEANS OF A GIVEN TYPE public class MyBean { @Inject @Any Instance<HelloService> services; public void displayHello() { for (HelloService service : services) { display( service.hello() ); } } }
  35. 35. SELECT A QUALIFIER AT RUNTIME public class MyBean { @Inject @Any Instance<HelloService> services; public void displayHello() { display( service.select( new AnnotationLiteral()<French> {}) .get() ); } }
  36. 36. CONTEXTS
  37. 37. CONTEXTS MANAGE BEANS LIFECYCLE • They helps container to choose when a bean should be instantiated and destroyed • They enforce the fact that a given bean is a singleton for a given context • Built-in CDI contexts : • @Dependent (default) • @ApplicationScoped, @SessionScoped, @RequestScoped • @ConversationScoped • @Singleton • You can create your own scope
  38. 38. CHOOSING THE RIGHT CONTEXT @SessionScoped public class CartBean { public void addItem(Item item) { ... } }
  39. 39. CHOOSING THE RIGHT CONTEXT @ApplicationScoped public class CartBean { public void addItem(Item item) { ... } }
  40. 40. CHOOSING THE RIGHT CONTEXT @ApplicationScoped public class CartBean { public void addItem(Item item) { ... } } FAIL !!!
  41. 41. CONVERSATION IS MANAGE BY DEV @ConversationScoped public class CartBean { public void addItem(Item item) { ... } }
  42. 42. NEW CONTEXTS CAN BE CREATED @ThreadScoped public class CartBean { public void addItem(Item item) { ... } }
  43. 43. PRODUCERS
  44. 44. CREATING BEAN FROM ANY CLASS @Produces public MyNonCDIClass myProducer() { return new MyNonCdiClass(); } ... @Inject MyNonCDIClass bean;
  45. 45. PRODUCERS MAY HAVE A SCOPE @Produces @RequestScoped public FacesContext produceFacesContext() { return FacesContext.getCurrentInstance(); }
  46. 46. GETTING INFO FROM INJECTION POINT @Produces public Logger produceLog(InjectionPoint injectionPoint) { return Logger.getLogger(injectionPoint.getMember() .getDeclaringClass().getName()); }
  47. 47. EVENTS
  48. 48. A NICE WAY TO ADD DECOUPLING public class FirstBean { @Inject Event<Post> postEvent; public void saveNewPost(Post myPost) { postEvent.fire(myPost); } } public class SecondBean { public void listenPost(@Observes Post post) { System.out.println("Received : " + evt.message()); } }
  49. 49. EVENTS CAN BE QUALIFIED public class FirstBean { @Inject Event<Post> postEvent; public void saveNewPost(Post myPost) { postEvent.select( new AnnotationLiteral()<French> {}).fire(myPost); } } public class SecondBean { // these 3 observers will be called public void listenFrPost(@Observes @French Post post) {} public void listenPost(@Observes Post post) {} public void listenObject(@Observes Object obj) {} // This one won’t be called public void listenEnPost(@Observes @English Post post) {} }
  50. 50. AS ALWAYS “NO TYPE ERASURE” public class SecondBean { // these observers will be resolved depending // on parameter in event payload type public void listenStrPost(@Observes Post<String> post) {} public void listenNumPost(@Observes Post<Number> post) {} }
  51. 51. SOME BUILT-IN EVENTS public class SecondBean { public void beginRequest(@Observes @Initialized(RequestScoped.class) ServletRequest req) {} public void endRequest(@Observes @Destroyed(RequestScoped.class) ServletRequest req) {} public void beginSession(@Observes @Initialized(SessionScoped.class) HttpSession session) {} public void endSession(@Observes @Destroyed(SessionScoped.class) HttpSession session) {} }
  52. 52. STEREOTYPES TO AVOID ANNOTATIONS HELL
  53. 53. BUILT-IN STEREOTYPE @Named @RequestScoped @Documented @Stereotype @Target({ TYPE, METHOD, FIELD }) @Retention(RUNTIME) public @interface Model { }
  54. 54. MY STEREOTYPE @Named @SessionScoped @MyQualifier @MyOtherQualifier @Documented @Stereotype @Target({ TYPE, METHOD, FIELD }) @Retention(RUNTIME) public @interface MyModel { }
  55. 55. USAGE @MyModel public class CircularBean { }
  56. 56. DECORATORS & INTERCEPTORS
  57. 57. A DECORATOR @Decorator @Priority(Interceptor.Priority.APPLICATION) public abstract class HelloDecorator implements HelloService { // The decorated service may be restricted with qualifiers @Inject @Delegate HelloService service; public String hello() { return service.hello() + "-decorated"; } }
  58. 58. INTERCEPTOR BINDING… @InterceptorBinding @Target({METHOD, TYPE}) @Retention(RUNTIME) public @interface Loggable {}
  59. 59. …IS USED TO BIND AN INTERCEPTOR @Interceptor @Loggable @Priority(Interceptor.Priority.APPLICATION) public class LogInterceptor { @AroundInvoke public Object log(InvocationContext ic) throws Exception { System.out.println("Entering " + ic.getMethod().getName()); try { return ic.proceed(); } finally { System.out.println("Exiting " + ic.getMethod().getName()); } } }
  60. 60. IT CAN BE PUT ON CLASS OR METHOD @Loggable public class MyBean { @Inject HelloService service; public void displayHello() { display( service.hello(); } }
  61. 61. THAT’S ALL FOR BASIC CDI • If you want to learn advanced stuff come to check my over talk : CDI advanced. • follow @cdispec and @antoine_sd on twitter • Questions ?

×