SlideShare une entreprise Scribd logo
1  sur  45
Télécharger pour lire hors ligne
Designing Java EE
Applications in the Age of CDI

      Michael Nascimento Santos
           Michel Graciano

            JavaOne 2012
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 Java

04/12/2012            Designing Java EE Applications in the Age of CDI   2
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 Developer's
       Conference and JavaOne



04/12/2012           Designing Java EE Applications in the Age of CDI   3
Agenda
     • CDI crash-course
     • CDI unique features
     • Putting it all together
              Demos
     • Q&A




04/12/2012             Designing Java EE Applications in the Age of CDI   4
Terminology
     • JSR 299 - CDI
              Contexts and Dependency Injection for the Java
               EE platform
     • Weld
              JSR-299 Reference Implementation




04/12/2012                 Designing Java EE Applications in the Age of CDI   5
“CDI is more than a framework. It's a whole, rich
             programming model. The theme of CDI is loose-
                      coupling with strong typing.”
                            Weld specification




04/12/2012                  Designing Java EE Applications in the Age of CDI   6
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
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
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
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
CDI crash-course
     • Beans with special initialization can be
       constructed using producers

public 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
CDI crash-course
     • Beans with special initialization can be
       constructed using producers

public 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
CDI crash-course
     • Activation and some configuration is done by
       beans.xml file




04/12/2012           Designing Java EE Applications in the Age of CDI   13
But what's the point of
      CDI anyway?


04/12/2012   Designing Java EE Applications in the Age of CDI   14
Unique features
     •       Clean scope combination
     •       Event system
     •       AOP without interfaces
     •       Access to injection point
     •       Portable extensions




04/12/2012                 Designing Java EE Applications in the Age of CDI   15
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
Custom scopes
     • Seam
              RenderScoped
     • MyFaces CODI
              @ConversationScoped
              @WindowScoped
              @ViewAccessScoped
     • Apache DeltaSpike
              @TransactionScoped




04/12/2012               Designing Java EE Applications in the Age of CDI   17
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
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
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
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
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
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 environments


04/12/2012                  Designing Java EE Applications in the Age of CDI   23
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
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
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
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
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 point




04/12/2012            Designing Java EE Applications in the Age of CDI   28
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
Portable extensions


<T> void processAnnotatedType(@Observes final
<T> void processAnnotatedType(@Observes final
ProcessAnnotatedType<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
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
Putting it all together


04/12/2012          Designing Java EE Applications in the Age of CDI   32
Named queries are not safe




04/12/2012   Designing Java EE Applications in the Age of CDI   33
Named queries are not safe




04/12/2012   Designing Java EE Applications in the Age of CDI   34
Typesafe @TypedQuery




04/12/2012   Designing Java EE Applications in the Age of CDI   35
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
Demo


04/12/2012   Designing Java EE Applications in the Age of CDI   37
Features used
     • CDI
              Dependency injection
              Producer methods
              Access to the injection point
     • Annotation processors




04/12/2012                  Designing Java EE Applications in the Age of CDI   38
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 fly




04/12/2012          Designing Java EE Applications in the Age of CDI   39
Auto-generated MBeans




04/12/2012   Designing Java EE Applications in the Age of CDI   40
Demo


04/12/2012   Designing Java EE Applications in the Age of CDI   41
Features used
     • CDI
              Dependency injection
              Producer fields
              Portable extensions
              Callback events
              Interceptors
     • JMX
              MXBean
              DynamicMBean


04/12/2012                 Designing Java EE Applications in the Age of CDI   42
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 applications




04/12/2012          Designing Java EE Applications in the Age of CDI #ageofcdi   43
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
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

Contenu connexe

Tendances

Nilesh_Surange J2EE 9.5+ Years
Nilesh_Surange J2EE  9.5+ YearsNilesh_Surange J2EE  9.5+ Years
Nilesh_Surange J2EE 9.5+ Years
surange
 
TheSpringFramework
TheSpringFrameworkTheSpringFramework
TheSpringFramework
Shankar Nair
 
Resume_abir
Resume_abirResume_abir
Resume_abir
Abir De
 

Tendances (20)

Resume
ResumeResume
Resume
 
Burns jsf-confess-2015
Burns jsf-confess-2015Burns jsf-confess-2015
Burns jsf-confess-2015
 
Nilesh_Surange J2EE 9.5+ Years
Nilesh_Surange J2EE  9.5+ YearsNilesh_Surange J2EE  9.5+ Years
Nilesh_Surange J2EE 9.5+ Years
 
TheSpringFramework
TheSpringFrameworkTheSpringFramework
TheSpringFramework
 
Indranil_Bhowmick_Resume
Indranil_Bhowmick_ResumeIndranil_Bhowmick_Resume
Indranil_Bhowmick_Resume
 
Resume_abir
Resume_abirResume_abir
Resume_abir
 
Suresh Resume
Suresh ResumeSuresh Resume
Suresh Resume
 
Using SAP Crystal Reports as a Linked (Open) Data Front-End via ODBC
Using SAP Crystal Reports as a Linked (Open) Data Front-End via ODBCUsing SAP Crystal Reports as a Linked (Open) Data Front-End via ODBC
Using SAP Crystal Reports as a Linked (Open) Data Front-End via ODBC
 
Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.Ed presents JSF 2.2 and WebSocket to Gameduell.
Ed presents JSF 2.2 and WebSocket to Gameduell.
 
JavaFX 2 - A Java Developer's Guide (San Antonio JUG Version)
JavaFX 2 - A Java Developer's Guide (San Antonio JUG Version)JavaFX 2 - A Java Developer's Guide (San Antonio JUG Version)
JavaFX 2 - A Java Developer's Guide (San Antonio JUG Version)
 
JavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFacesJavaOne - 10 Tips for Java EE 7 with PrimeFaces
JavaOne - 10 Tips for Java EE 7 with PrimeFaces
 
Exploiting Linked Data via Filemaker
Exploiting Linked Data via FilemakerExploiting Linked Data via Filemaker
Exploiting Linked Data via Filemaker
 
Raveendra_Resume.DOC
Raveendra_Resume.DOCRaveendra_Resume.DOC
Raveendra_Resume.DOC
 
JSF 2.2
JSF 2.2JSF 2.2
JSF 2.2
 
JavaFX 2 Using the Spring Framework
JavaFX 2 Using the Spring FrameworkJavaFX 2 Using the Spring Framework
JavaFX 2 Using the Spring Framework
 
Oracle ADF Architecture TV - Deployment - Deployment Options
Oracle ADF Architecture TV - Deployment - Deployment OptionsOracle ADF Architecture TV - Deployment - Deployment Options
Oracle ADF Architecture TV - Deployment - Deployment Options
 
Professional Qualification
Professional QualificationProfessional Qualification
Professional Qualification
 
Abdul latif
Abdul latifAbdul latif
Abdul latif
 
Whats Next for JCA?
Whats Next for JCA?Whats Next for JCA?
Whats Next for JCA?
 
Designing JEE Application Structure
Designing JEE Application StructureDesigning JEE Application Structure
Designing JEE Application Structure
 

En vedette

Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 
Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014
Antoine Sabot-Durand
 

En vedette (12)

CDI and Seam 3: an Exciting New Landscape for Java EE Development
CDI and Seam 3: an Exciting New Landscape for Java EE DevelopmentCDI and Seam 3: an Exciting New Landscape for Java EE Development
CDI and Seam 3: an Exciting New Landscape for Java EE Development
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Moving to Java EE 6 and CDI and away from the clutter
Moving to Java EE 6 and CDI and away from the clutterMoving to Java EE 6 and CDI and away from the clutter
Moving to Java EE 6 and CDI and away from the clutter
 
Java EE 6
Java EE 6Java EE 6
Java EE 6
 
What we can expect from Java 9 by Ivan Krylov
What we can expect from Java 9 by Ivan KrylovWhat we can expect from Java 9 by Ivan Krylov
What we can expect from Java 9 by Ivan Krylov
 
CDI, Weld and the future of Seam
CDI, Weld and the future of SeamCDI, Weld and the future of Seam
CDI, Weld and the future of Seam
 
Seam 3 e CDI: O futuro do Java EE 6
Seam 3 e CDI: O futuro do Java EE 6Seam 3 e CDI: O futuro do Java EE 6
Seam 3 e CDI: O futuro do Java EE 6
 
Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014Introduction to cdi given at java one 2014
Introduction to cdi given at java one 2014
 
Extending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss ForgeExtending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss Forge
 
Java one 2015 [con3339]
Java one 2015 [con3339]Java one 2015 [con3339]
Java one 2015 [con3339]
 
Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...
Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...
Porque você deveria usar CDI nos seus projetos Java! - JavaOne LA 2012 - Sérg...
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJS
 

Similaire à Designing Java EE Applications in the Age of CDI

Arpan_Resume_Aug_2015
Arpan_Resume_Aug_2015Arpan_Resume_Aug_2015
Arpan_Resume_Aug_2015
arpan sarkar
 
Resume - Joydeep Lodh -Updated
Resume - Joydeep Lodh -UpdatedResume - Joydeep Lodh -Updated
Resume - Joydeep Lodh -Updated
Joydeep Lodh
 

Similaire à Designing Java EE Applications in the Age of CDI (20)

Managing Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsManaging Data in Jakarta EE Applications
Managing Data in Jakarta EE Applications
 
Arpan_Resume_Aug_2015
Arpan_Resume_Aug_2015Arpan_Resume_Aug_2015
Arpan_Resume_Aug_2015
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Java Spring
Java SpringJava Spring
Java Spring
 
Dependency Injection Styles
Dependency Injection StylesDependency Injection Styles
Dependency Injection Styles
 
Complete Dojo
Complete DojoComplete Dojo
Complete Dojo
 
EJB and CDI - Alignment and Strategy
EJB and CDI - Alignment and StrategyEJB and CDI - Alignment and Strategy
EJB and CDI - Alignment and Strategy
 
Vara Framework
Vara FrameworkVara Framework
Vara Framework
 
Subhadra Banerjee_latest
Subhadra Banerjee_latestSubhadra Banerjee_latest
Subhadra Banerjee_latest
 
Resume - Joydeep Lodh -Updated
Resume - Joydeep Lodh -UpdatedResume - Joydeep Lodh -Updated
Resume - Joydeep Lodh -Updated
 
Alex Theedom Java ee revisits design patterns
Alex Theedom	Java ee revisits design patternsAlex Theedom	Java ee revisits design patterns
Alex Theedom Java ee revisits design patterns
 
SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"SE2016 Java Alex Theedom "Java EE revisits design patterns"
SE2016 Java Alex Theedom "Java EE revisits design patterns"
 
Partner Webcast – Oracle Public Cloud for ISVs: Migrating Java EE and ADF app...
Partner Webcast – Oracle Public Cloud for ISVs: Migrating Java EE and ADF app...Partner Webcast – Oracle Public Cloud for ISVs: Migrating Java EE and ADF app...
Partner Webcast – Oracle Public Cloud for ISVs: Migrating Java EE and ADF app...
 
Cloud Foundry Summit 2015: A Year of Innovation: Cloud Foundry Lessons Learned
Cloud Foundry Summit 2015: A Year of Innovation: Cloud Foundry Lessons LearnedCloud Foundry Summit 2015: A Year of Innovation: Cloud Foundry Lessons Learned
Cloud Foundry Summit 2015: A Year of Innovation: Cloud Foundry Lessons Learned
 
Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?Java v/s .NET - Which is Better?
Java v/s .NET - Which is Better?
 
Projects delivered
Projects deliveredProjects delivered
Projects delivered
 
deep learning in production cff 2017
deep learning in production cff 2017deep learning in production cff 2017
deep learning in production cff 2017
 
Sightly_techInsight
Sightly_techInsightSightly_techInsight
Sightly_techInsight
 
Dirigible powered by Orion for Cloud Development (EclipseCon EU 2015)
Dirigible powered by Orion for Cloud Development (EclipseCon EU 2015)Dirigible powered by Orion for Cloud Development (EclipseCon EU 2015)
Dirigible powered by Orion for Cloud Development (EclipseCon EU 2015)
 
Developing Java EE Applications on IntelliJ IDEA with Oracle WebLogic 12c
Developing Java EE Applications on IntelliJ IDEA with Oracle WebLogic 12cDeveloping Java EE Applications on IntelliJ IDEA with Oracle WebLogic 12c
Developing Java EE Applications on IntelliJ IDEA with Oracle WebLogic 12c
 

Plus de Michel Graciano

Introdução a CDI e como utilizá-la em aplicações reais
Introdução a CDI e como utilizá-la em aplicações reaisIntrodução a CDI e como utilizá-la em aplicações reais
Introdução a CDI e como utilizá-la em aplicações reais
Michel Graciano
 

Plus de Michel Graciano (7)

Aplicando CDI em aplicações Java
Aplicando CDI em aplicações JavaAplicando CDI em aplicações Java
Aplicando CDI em aplicações Java
 
O papel e a carreira de um desenvolvedor de software
O papel e a carreira de um desenvolvedor de softwareO papel e a carreira de um desenvolvedor de software
O papel e a carreira de um desenvolvedor de software
 
Finalmente java sabe trabalhar com data e hora (gu java sc)
Finalmente java sabe trabalhar com data e hora (gu java sc)Finalmente java sabe trabalhar com data e hora (gu java sc)
Finalmente java sabe trabalhar com data e hora (gu java sc)
 
CON6423: Scalable JavaScript applications with Project Nashorn
CON6423: Scalable JavaScript applications with Project NashornCON6423: Scalable JavaScript applications with Project Nashorn
CON6423: Scalable JavaScript applications with Project Nashorn
 
Finalmente java sabe trabalhar com data e hora
Finalmente java sabe trabalhar com data e horaFinalmente java sabe trabalhar com data e hora
Finalmente java sabe trabalhar com data e hora
 
Introdução a CDI e como utilizá-la em aplicações reais
Introdução a CDI e como utilizá-la em aplicações reaisIntrodução a CDI e como utilizá-la em aplicações reais
Introdução a CDI e como utilizá-la em aplicações reais
 
genesis - Acelerando o desenvolvimento de aplicações desktop
genesis - Acelerando o desenvolvimento de aplicações desktopgenesis - Acelerando o desenvolvimento de aplicações desktop
genesis - Acelerando o desenvolvimento de aplicações desktop
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Designing Java EE Applications in the Age of CDI

  • 1. Designing Java EE Applications in the Age of CDI Michael Nascimento Santos Michel Graciano JavaOne 2012
  • 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 Java 04/12/2012 Designing Java EE Applications in the Age of CDI 2
  • 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 Developer's Conference and JavaOne 04/12/2012 Designing Java EE Applications in the Age of CDI 3
  • 4. Agenda • CDI crash-course • CDI unique features • Putting it all together  Demos • Q&A 04/12/2012 Designing Java EE Applications in the Age of CDI 4
  • 5. Terminology • JSR 299 - CDI  Contexts and Dependency Injection for the Java EE platform • Weld  JSR-299 Reference Implementation 04/12/2012 Designing Java EE Applications in the Age of CDI 5
  • 6. “CDI is more than a framework. It's a whole, rich programming model. The theme of CDI is loose- coupling with strong typing.” Weld specification 04/12/2012 Designing Java EE Applications in the Age of CDI 6
  • 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. 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. 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. 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. CDI crash-course • Beans with special initialization can be constructed using producers public 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. CDI crash-course • Beans with special initialization can be constructed using producers public 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. CDI crash-course • Activation and some configuration is done by beans.xml file 04/12/2012 Designing Java EE Applications in the Age of CDI 13
  • 14. But what's the point of CDI anyway? 04/12/2012 Designing Java EE Applications in the Age of CDI 14
  • 15. Unique features • Clean scope combination • Event system • AOP without interfaces • Access to injection point • Portable extensions 04/12/2012 Designing Java EE Applications in the Age of CDI 15
  • 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. Custom scopes • Seam  RenderScoped • MyFaces CODI  @ConversationScoped  @WindowScoped  @ViewAccessScoped • Apache DeltaSpike  @TransactionScoped 04/12/2012 Designing Java EE Applications in the Age of CDI 17
  • 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. 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. 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. 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. 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. 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 environments 04/12/2012 Designing Java EE Applications in the Age of CDI 23
  • 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. 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. 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. 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. 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 point 04/12/2012 Designing Java EE Applications in the Age of CDI 28
  • 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. Portable extensions <T> void processAnnotatedType(@Observes final <T> void processAnnotatedType(@Observes final ProcessAnnotatedType<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. 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. Putting it all together 04/12/2012 Designing Java EE Applications in the Age of CDI 32
  • 33. Named queries are not safe 04/12/2012 Designing Java EE Applications in the Age of CDI 33
  • 34. Named queries are not safe 04/12/2012 Designing Java EE Applications in the Age of CDI 34
  • 35. Typesafe @TypedQuery 04/12/2012 Designing Java EE Applications in the Age of CDI 35
  • 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. Demo 04/12/2012 Designing Java EE Applications in the Age of CDI 37
  • 38. Features used • CDI  Dependency injection  Producer methods  Access to the injection point • Annotation processors 04/12/2012 Designing Java EE Applications in the Age of CDI 38
  • 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 fly 04/12/2012 Designing Java EE Applications in the Age of CDI 39
  • 40. Auto-generated MBeans 04/12/2012 Designing Java EE Applications in the Age of CDI 40
  • 41. Demo 04/12/2012 Designing Java EE Applications in the Age of CDI 41
  • 42. Features used • CDI  Dependency injection  Producer fields  Portable extensions  Callback events  Interceptors • JMX  MXBean  DynamicMBean 04/12/2012 Designing Java EE Applications in the Age of CDI 42
  • 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 applications 04/12/2012 Designing Java EE Applications in the Age of CDI #ageofcdi 43
  • 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. 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