Designing Java EE Applications in the Age of CDI

2,847 views

Published on

Even though CDI has been available since the end of 2009, most people still do not realize its full power and the possibilities it brings. Attend this session to understand which CDI features make it excel in comparison with other dependency-injection-based solutions and see how they can be used to design flexible applications and frameworks that will stand the test of time.

Published in: Technology

Designing Java EE Applications in the Age of CDI

  1. 1. Designing Java EEApplications in the Age of CDI Michael Nascimento Santos Michel Graciano JavaOne 2012
  2. 2. Michael Nascimento Santos • +13 years of Java experience, from Java ME to Java EE, and over 19 years of practical programming experience • JSR-310 (Date and Time API) co-leader and expert at JSRs 207, 250, 270 (Java SE 6), 296 (Swing Application Framework), 303 (Bean Validation), 349 (Bean Validation 1.1) • genesis (http://java.net/projects/genesis) and ThinNB (http://java.net/projects/thinnb) founder • JavaOne Rock Star Speaker and speaker at JustJava, Abaporu, FISL, COMDEX, BrasilOne and Conexão Java04/12/2012 Designing Java EE Applications in the Age of CDI 2
  3. 3. Michel Graciano • +9 years of experience with the Java platform • Former NetBeans translation project coordenator and contributor • Active open source member of NetBeans and other projects • Committer of genesis (http://java.net/projects/genesis) • Speaker at JustJava, The Developers Conference and JavaOne04/12/2012 Designing Java EE Applications in the Age of CDI 3
  4. 4. Agenda • CDI crash-course • CDI unique features • Putting it all together  Demos • Q&A04/12/2012 Designing Java EE Applications in the Age of CDI 4
  5. 5. Terminology • JSR 299 - CDI  Contexts and Dependency Injection for the Java EE platform • Weld  JSR-299 Reference Implementation04/12/2012 Designing Java EE Applications in the Age of CDI 5
  6. 6. “CDI is more than a framework. Its a whole, rich programming model. The theme of CDI is loose- coupling with strong typing.” Weld specification04/12/2012 Designing Java EE Applications in the Age of CDI 6
  7. 7. CDI crash-course • Beans can be injected using @Inject • Injected beans can be filtered and/or disambiguated using @Qualifier @Inject @Inject Greeting greeting; Greeting greeting;04/12/2012 Designing Java EE Applications in the Age of CDI 7
  8. 8. CDI crash-course • Beans can be injected using @Inject • Injected beans can be filtered and/or disambiguated using @Qualifier @Informal @Informal @Inject @Inject Greeting greeting; Greeting greeting;04/12/2012 Designing Java EE Applications in the Age of CDI 8
  9. 9. CDI crash-course @Qualifier @Qualifier @Retention(RUNTIME) @Retention(RUNTIME) @Target({METHOD, FIELD, PARAMETER, TYPE}) @Target({METHOD, FIELD, PARAMETER, TYPE}) public @interface Informal { public @interface Informal { } }04/12/2012 Designing Java EE Applications in the Age of CDI #ageofcdi 9
  10. 10. CDI crash-course • Beans can be named using @Named @Named(“pageModel”) @Named(“pageModel”) public class PageModel { public class PageModel { public getName() { ... } public getName() { ... } } } <h:body> <h:body> #{pageModel.name} #{pageModel.name} </h:body> </h:body>04/12/2012 Designing Java EE Applications in the Age of CDI 10
  11. 11. CDI crash-course • Beans with special initialization can be constructed using producerspublic class Shop {public class Shop { @Produces @Produces PaymentProcessor getPaymentProcessor() { ... } PaymentProcessor getPaymentProcessor() { ... } @Produces @Produces List<Product> getProducts() { ... } List<Product> getProducts() { ... }}}04/12/2012 Designing Java EE Applications in the Age of CDI 11
  12. 12. CDI crash-course • Beans with special initialization can be constructed using producerspublic class Shop {public class Shop { @Produces @Produces @ApplicationScoped @ApplicationScoped @Catalog @Catalog @Named("catalog") @Named("catalog") List<Product> getProducts() { ... } List<Product> getProducts() { ... }}}04/12/2012 Designing Java EE Applications in the Age of CDI 12
  13. 13. CDI crash-course • Activation and some configuration is done by beans.xml file04/12/2012 Designing Java EE Applications in the Age of CDI 13
  14. 14. But whats the point of CDI anyway?04/12/2012 Designing Java EE Applications in the Age of CDI 14
  15. 15. Unique features • Clean scope combination • Event system • AOP without interfaces • Access to injection point • Portable extensions04/12/2012 Designing Java EE Applications in the Age of CDI 15
  16. 16. Clean scope combination • Scopes determine the bean instances lifecycle and can be safely combined as needed @SessionScoped @SessionScoped public class User implements Serializable public class User implements Serializable { ... } { ... } @ApplicationScoped @ApplicationScoped public class System implements Serializable public class System implements Serializable { { @Inject @Inject User user; User user; ... ... } }04/12/2012 Designing Java EE Applications in the Age of CDI 16
  17. 17. Custom scopes • Seam  RenderScoped • MyFaces CODI  @ConversationScoped  @WindowScoped  @ViewAccessScoped • Apache DeltaSpike  @TransactionScoped04/12/2012 Designing Java EE Applications in the Age of CDI 17
  18. 18. Event system • Loose-decoupled event producers from consumers by the event notifications model • Events can be filtered using qualifiers public void onAnyDocumentEvent( public void onAnyDocumentEvent( @Observes Document document) { ... } @Observes Document document) { ... } public void afterDocumentUpdate( public void afterDocumentUpdate( @Observes @Updated Document document) @Observes @Updated Document document) { ... } { ... }04/12/2012 Designing Java EE Applications in the Age of CDI 18
  19. 19. Event system • Loose-decoupled event producers from consumers by the event notifications model • Events can be filtered using qualifiers @Inject @Any Event<Document> event; @Inject @Any Event<Document> event; ... ... public void someMethod() { public void someMethod() { event.fire(document); event.fire(document); } }04/12/2012 Designing Java EE Applications in the Age of CDI 19
  20. 20. Event system • Loose-decoupled event producers from consumers by the event notifications model • Events can be filtered using qualifiers @Inject @Updated Event<Document> event; @Inject @Updated Event<Document> event; ... ... public void someMethod() { public void someMethod() { event.fire(document); event.fire(document); } }04/12/2012 Designing Java EE Applications in the Age of CDI 20
  21. 21. Event system • Conditional observers  IF_EXISTS  ALWAYS public void afterDocumentUpdate( public void afterDocumentUpdate( @Observes(receive=IF_EXISTS) @Observes(receive=IF_EXISTS) @Updated Document document) { ... } @Updated Document document) { ... }04/12/2012 Designing Java EE Applications in the Age of CDI 21
  22. 22. Event system • Transactional observers  IN_PROGRESS,  BEFORE_COMPLETION,  AFTER_COMPLETION,  AFTER_FAILURE,  AFTER_SUCCESS public void afterDocumentUpdate( public void afterDocumentUpdate( @Observes(during=AFTER_SUCCESS) @Observes(during=AFTER_SUCCESS) @Updated Document document) { ... } @Updated Document document) { ... }04/12/2012 Designing Java EE Applications in the Age of CDI 22
  23. 23. AOP without interfaces • Interceptors decouple technical concerns from business logic  Orthogonal to the application and type system • Decorators allow business concerns to be compartmentalized using the interceptor concept  Attached to a Java type, aware of business semantics • Configurable  Enabled and ordered at beans.xml file, allowing different behaviours for different environments04/12/2012 Designing Java EE Applications in the Age of CDI 23
  24. 24. Interceptors @Inherited @Inherited @InterceptorBinding @InterceptorBinding @Target({TYPE, METHOD}) @Target({TYPE, METHOD}) @Retention(RUNTIME) @Retention(RUNTIME) public @interface Secure {} public @interface Secure {}04/12/2012 Designing Java EE Applications in the Age of CDI 24
  25. 25. Interceptors @Secure @Secure @Interceptor @Interceptor public class SecurityInterceptor { public class SecurityInterceptor { @AroundInvoke @AroundInvoke public Object manageSecurity( public Object manageSecurity( InvocationContext ctx) throws Exception { InvocationContext ctx) throws Exception { // manage security... // manage security... return ctx.proceed(); return ctx.proceed(); } } } }04/12/2012 Designing Java EE Applications in the Age of CDI 25
  26. 26. Interceptors public class ShoppingCart { public class ShoppingCart { @Secure @Secure public void placeOrder() { ... } public void placeOrder() { ... } } } @Secure @Secure public class System { public class System { ... ... } }04/12/2012 Designing Java EE Applications in the Age of CDI 26
  27. 27. Decorators @Decorator @Decorator class TimestampLogger implements class TimestampLogger implements Logger { Logger { @Inject @Delegate @Any Logger @Inject @Delegate @Any Logger logger; logger; @Override @Override void log(String message) { void log(String message) { logger.log( timestamp() + ": " + logger.log( timestamp() + ": " + message ); message ); } } ... ... } }04/12/2012 Designing Java EE Applications in the Age of CDI 27
  28. 28. Access to injection point • Allowed at @Dependent scoped beans to obtain information about the injection point to which they belong • Empowers producers with the ability to react according to the injection point04/12/2012 Designing Java EE Applications in the Age of CDI 28
  29. 29. Access to injection point @Produces @Produces Logger createLogger(InjectionPoint ip) { Logger createLogger(InjectionPoint ip) { return Logger.getLogger( return Logger.getLogger( ip.getMember().getDeclaringClass(). ip.getMember().getDeclaringClass(). getName()); getName()); } } public class SomeClass { public class SomeClass { @Inject @Inject Logger logger; Logger logger; ... ... } }04/12/2012 Designing Java EE Applications in the Age of CDI 29
  30. 30. Portable extensions<T> void processAnnotatedType(@Observes final<T> void processAnnotatedType(@Observes finalProcessAnnotatedType<T> pat) {ProcessAnnotatedType<T> pat) { final AnnotatedTypeBuilder builder = final AnnotatedTypeBuilder builder = new AnnotatedTypeBuilder(). new AnnotatedTypeBuilder(). readFromType(pat.getAnnotatedType(), readFromType(pat.getAnnotatedType(), true).addToClass(NamedLiteral.INSTANCE); true).addToClass(NamedLiteral.INSTANCE); pat.setAnnotatedType(builder.create()); pat.setAnnotatedType(builder.create());}}04/12/2012 Designing Java EE Applications in the Age of CDI 30
  31. 31. Portable extensions <X> void processInjectionTarget(@Observes <X> void processInjectionTarget(@Observes ProcessInjectionTarget<X> pit) { ProcessInjectionTarget<X> pit) { for (InjectionPoint ip : for (InjectionPoint ip : pit.getInjectionTarget(). pit.getInjectionTarget(). getInjectionPoints()) { getInjectionPoints()) { ... ... } } } }04/12/2012 Designing Java EE Applications in the Age of CDI 31
  32. 32. Putting it all together04/12/2012 Designing Java EE Applications in the Age of CDI 32
  33. 33. Named queries are not safe04/12/2012 Designing Java EE Applications in the Age of CDI 33
  34. 34. Named queries are not safe04/12/2012 Designing Java EE Applications in the Age of CDI 34
  35. 35. Typesafe @TypedQuery04/12/2012 Designing Java EE Applications in the Age of CDI 35
  36. 36. Typesafe @TypedQuery ------------------------------------------------------------- ------------------------------------------------------------- COMPILATION ERROR :: COMPILATION ERROR ------------------------------------------------------------- ------------------------------------------------------------- and returns false. and returns false. model/CustomerModel.java:[47,25] error: Named query Customer.findByNme not defined yet. model/CustomerModel.java:[47,25] error: Named query Customer.findByNme not defined yet. model/CustomerModel.java:[43,25] error: Named query Customer.findAl not defined yet. model/CustomerModel.java:[43,25] error: Named query Customer.findAl not defined yet. 2 errors 2 errors ------------------------------------------------------------- -------------------------------------------------------------04/12/2012 Designing Java EE Applications in the Age of CDI 36
  37. 37. Demo04/12/2012 Designing Java EE Applications in the Age of CDI 37
  38. 38. Features used • CDI  Dependency injection  Producer methods  Access to the injection point • Annotation processors04/12/2012 Designing Java EE Applications in the Age of CDI 38
  39. 39. Auto-generated MBeans • Portable extensions and event system allow deployed components to be easily detected • Provide good entry point for enabling management for CDI components • Metadata can be used to generate JMX MBeans on the fly04/12/2012 Designing Java EE Applications in the Age of CDI 39
  40. 40. Auto-generated MBeans04/12/2012 Designing Java EE Applications in the Age of CDI 40
  41. 41. Demo04/12/2012 Designing Java EE Applications in the Age of CDI 41
  42. 42. Features used • CDI  Dependency injection  Producer fields  Portable extensions  Callback events  Interceptors • JMX  MXBean  DynamicMBean04/12/2012 Designing Java EE Applications in the Age of CDI 42
  43. 43. Conclusion • CDI is more than a simple dependency injection framework • Unique features like access to injection point information, events and portable extensions enable creative typesafe solutions to be explored • It is a new era, the age of CDI, so keep this in mind when designing your JavaEE applications04/12/2012 Designing Java EE Applications in the Age of CDI #ageofcdi 43
  44. 44. Q&A Michael N. Santos | @mr__m http://blog.michaelnascimento.com.br/ michael.nascimento@tecsinapse.com.br Michel Graciano | @mgraciano http://www.summa.com.br/ michel.graciano@summa.com.br https://github.com/mgraciano/javaone-2012/12/04/12 Designing Java EE Applications in the Age of CDI 44
  45. 45. Thank you Michael N. Santos | @mr__m http://blog.michaelnascimento.com.br/ michael.nascimento@tecsinapse.com.br Michel Graciano | @mgraciano http://www.summa.com.br/ michel.graciano@summa.com.br https://github.com/mgraciano/javaone-2012/12/04/12 Designing Java EE Applications in the Age of CDI #ageofcdi 45

×