Introduction to CDI and DI in Java EE 6


Published on

Published in: Technology
1 Comment
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • What if I told you there was a way to be more productive as a developer?What if I told you that you would need to write up to 50% less code to build your application?What if I told you that your application would need 25% less classes?What if I told you that you could reduce your XML configs by 80%?What if I told you that you could start your container in 75% less time then previously?What if I told you that this was all a standard?What if I told you that there’s tooling to make the development of modern applications even faster?Sounds fantastic right? I hope that all of you will be as interested as I have been in the subject
  • Sounds Fantastic, right?What if I were to tell you it was all based on Java EE 6?Does Java EE really offer benefits?
  • Many of you may be as skeptical and confused as I was. The J2EE of the past has a terrible reputation for being riddled with undue complexity.
  • At the time, J2EE 1.4 did facilitate many innovations and enhancements. But itsIn the past, Java EE allowed developers to accomplish tasks but was not nearly as efficient as it could beLots of unnecessary work was required – extra interfaces, extra code, extra configuration
  • Creating an EJB was a multiple-step exercise:In this example we want to create a simple Bank Enterprsie Java Bean.Creating the local interface, creating the local home interface, creating the remote interface and creating the bean. This was all just to create in this application a simple bean to process deposits and transfers
  • Not only was the code inefficient, so was the configuration of that code
  • Even the access of the components held lots of room for improvement. Looss at this example above – All we wanted to do is invoke the deposit method on the bank object. 75% has nothing to do with our achieving the goals of our business.
  • As demonstrated by our previous example,there were challenges. These challenges have been etched on the collective mind of developers for a long time now.
  • Today we need technology that is modern and relevant for todays enterprise needs.
  • Events, interceptors and decorators enhance the loose-coupling that is inherent in this model:event notifications decouple event producers from event consumersinterceptors decouple technical concerns from business logicdecorators allow business concerns to be compartmentalized
  • JSR-299 defines a unifying dependency injection and contextual lifecycle model for Java EE 6 a completely new, richer dependency management model designed for use with stateful objects integrates the “web” and “transactional” tiers makes it much easier to build applications using JSF and EJB together includes a complete SPI allowing third-party frameworks to integrate cleanly in the EE 6 environment
  • JSF2 + RichFaces – JBoss and open source led many advancements to the EE6 specification, JSF 2.0 has had numerous enhancements such as Facelets, an XHTML-layout solution, built-in AJAX support (modeled on RichFace's A4J) and BeanValidation (lead by Emmanuel Bernard and  Hibernate Validator).   RichFaces 4.0 extends JSF 2.0 with not only numerous components such as trees, tabs and menus but also provides a Component Development Kit (CDK) to allow you to build your own custom extensions as well as integration with other EE specs like JMS and CDI.  In addition, with RichFaces 4.0, we have made RichFaces & JSF ready for mobile web applications. Demo: showing how server-side entity-based, declarative, BeanValidation's 'float' to the browser via RichFaces - a change to the JPA entity's validation annotations are immediately seen on the end-user's browser-based application - one validator to rule them all.HTML5 + Aerogear – HTML5 + CSS3 + JavaScript with libraries like jQuery/jQuery Mobile. POH5 – Plain Old HTML5 – build your mobile and desktop applications using rich clients written in the browser’s native language and HTML5 introduces many new features for the average enterprise application such as: new form fields like email, websockets and local device storage. Aerogear is focused on community, innovation and education – bringing you the best examples, tutorials and techniques for building mobile web and hybrid/native apps on JBoss. Key Demo: publishing the poh5 archetype kitchensink to openshift, providing a URL to the audience then pushing a POH5-application all the way through phonegap, it is now in the app store, try it on your phone right nowGWT + Errai – Google Web Toolkit targets developers who are productive with Java, and wish to develop performant AJAXy applications with rich behavior on the client side. GWT’s Java-to-JavaScript compiler allows the Java developer to work with his normal editor (JBDS5/Eclipse), debugger and refactoring tools – to manage the large codebases that come with true rich client development. Errai makes large maintainable rich clients a reality by extending GWT with the power of CDI, @Inject into browser/client code, a simple and flexible object marshalling facility, and over-the-wire CDI eventing for a loosely-coupled client-server application with high-performance bi-directional push, and shared code between client and server.Key Demo: showing how kitchensink members/records added in Chrome are immediately pushed to Firefox – all users see all data, instantly and the client & server programming model is simple EE6 CDI annotations
  • * Use backbone.js to structure application* jqueryMobile for mobile portionBackbone* model components hold data, hand data change events and perform CRUD on REST endpoints - most domain entities mirrored by backbone model* views render the UI by manipulating the DOM* router executes actions in response to hashchange - equivalent to page navigations
  • JBoss Central in JBoss Developer Studio 5.0 Beta 1 provides EE6, HTML5+Aerogear/jQuery, JSF2+RichFaces, SpringMVC and GWT+Errai Maven archetypes. No more guessing about your maven dependencies. In addition, links to the latest developer-facing news, forums and documentation is immediately available. The Software/Update tab points out specific 3rd party Eclipse plugins such as SpringIDE, Google Plug-In for Eclipse and JRebel which compliment JBoss Developer Studio and JBoss Tools.
  • JBoss Developer Studio 5 comes with a special webkit-based mobile browser simulator – this allows you to get a quick preview of what your mobile web application will look like – then when you are ready to test the application on real smartphones and tablets simply push it to OpenShift for everyone to try it.
  • Introduction to CDI and DI in Java EE 6

    1. 1. Productive,LEARNING CDI Simple, Modern Ray Ploski Director, Developer Programs & Strategy JBoss, by Red Hat, Inc.
    2. 2. AGENDA Background Concepts Status & Roadmap
    3. 3. DEVELOPER PRODUCTIVITY - WHAT IF? Faster Start-Up Times 80% Less Configuration 50% Less Code Open eco-system 25% Less Classes Vendor Agnostic Rapid Application Tooling Easier Integration Testing* Based on a Sample POJO/JPA/REST Based Application
    4. 4. GREAT !!!
    5. 5. J2EE #fail #fail EJB #fail
    6. 6. EJB 2.X SESSION BEAN
    7. 7. EJB 2.X DEPLOYMENT DESCRIPTOR<!-- … --><enterprise-beans> <session> <display-name>BankSB</display-name> <ejb-name>BankBean</ejb-name> <local-home>com.advocacy.legacy.ejb.BankLocalHome</local-home> <local>com.advocacy.legacy.ejb.BankLocal</local> <ejb-class>com.advocacy.legacy.ejb.BankBean</ejb-class> <session-type>Stateless</session-type> <transaction-type>Container</transaction-type> </session></enterprise-beans><assembly-descriptor> <container-transaction> <method> <ejb-name>BankSB</ejb-name> <method-name>*</method-name> </container-transaction></assembly-descriptor>
    8. 8. EJB 2.X CLIENT VIEW
    9. 9. J2EE #fail #fail EJB #fail
    10. 10. JAVA EE 5 Annotation Enhancements Resource injection in JEE5  @EJB, @Resource, @PersistenceContext,  @PersistenceUnit Into Container Components:  Servlets, JSF backing beans and other EJBs Progress but still Problems  No POJOs  Cannot inject DAOs or helper classes that were not written as EJBs  Hard to integrate anything but strictly business components
    11. 11. Java EE 6
    12. 12. JAVA EE 6The EE 6 web profile removes most ofthe “cruft” that has developed overthe years  mainly totally useless stuff like web services, EJB 2 entity beans etc.  some useful stuff (e.g. JMS) is missing, but vendors can include it
    15. 15. EJB 3.1 CLIENT VIEW@EJB BankLocal bank;public void makeDeposit(){ bank.deposit(2500.00, new Account(12345));}
    16. 16. HOW DID THEY DO THAT?Configuration by exception with sensible defaults  Security permissions defaults to UNCHECKED  Transaction type defaults to CONTAINER  Transaction attribute defaults to REQUIREDUse Annotations  To choose explicitly (recommended)  To override defaultsDeployment descriptor is no longer required  But can override above configurations
    17. 17. EASE OF USE IMPROVEMENTS Optional Local Interface Simplified Packaging EJB-Lite Portable JNDI Naming Simple Component Testing
    18. 18. JAVA EE 6 EJB 3.1 - asynch, no-interface views, embeddable JPA 2.0 - typesafe criteria API, many more O/R mapping options JSF 2.0 - Ajax, easy component creation, bookmarkable URLs Bean Validation 1.0 - annotation-based validation API Servlet 3.0 - async support, better support for frameworks Standard global JNDI names Managed Beans
    19. 19. MANAGED BEANSContainer-managed POJOs with minimal requirementssupport a set of basic services  resource injection  lifecycle callbacks  interceptors
    20. 20. MANAGED BEANS the foundation for all other component types in the platform core services centralized under Managed Beans Other specifications will add support for additional services remoting instance pooling web services
    21. 21. AGENDA Background Concepts Status & Roadmap
    22. 22. Loose CouplingSTRONG TYPING
    23. 23. DEPENDENCY INJECTION IN TWO PARTSDI (@Inject) CDIJSR 330 JSR 299javax.inject javax.enterprise.context@Inject Alternatives@Named Producers@Singleton Scopes@Qualifier Stereotypes@Scope Decorators Extensions
    24. 24. SIMPLE EXAMPLEpublic class Hello { Any Managed Bean public String sayHello(String name) { can use these return "hello" + name; } services}@Stateless So can EJBspublic class Hello { public String sayHello(String name) { return "hello" + name; }}
    25. 25. SIMPLE EXAMPLE @Inject defines anpublic class Printer { injection point. @Inject Hello hello; @Default qualifier is assumed public void printHello() { System.out.println( hello.sayHello("world") ); }}
    26. 26. CONSTRUCTOR INJECTIONpublic class Printer { Mark the constructor to be private Hello hello; called by the container @Inject @Inject public Printer(Hello hello) { this.hello=hello; } public void printHello() { System.out.println( hello.sayHello("world") ); }} Constructors are injected by default; @Default is the default qualifier
    27. 27. MANAGED BEAN NAMES By default not@Named("hello")public class Hello { available through EL. public String sayHello(String name) { return "hello" + name; }} If no name is specified, then a default name is used. Both these Managed Beans have@Named the same namepublic class Hello { public String sayHello(String name) { return "hello" + name; }}
    28. 28. JSF PAGE<h:commandButton value=“Say Hello” action=“#{hello.sayHello}”/> Calling an action on a bean through EL
    29. 29. WHAT MAKES CDI UNIQUE? Standard Type SafeExtensible
    30. 30. DEFINING THE QUALIFIER@Qualifier@Retention (RUNTIME)@Target({FIELD,TYPE,METHOD,PARAMETER})public @interface NumberOfDigits { Digits value();} Creating a qualifer is really easy!public enum Digits { TWO, EIGHT, TEN, THIRTEEN} Example Credit: Antonio Goncalves
    31. 31. DEFINING THE BEANS@NumberOfDigits (Digits.EIGHT)public class IssnGenerator { public String generateNumber() { We specify the return “8-” + nextNumber(); @NumberOfDigits } qualifier. If no qualifer is} specified on a bean, @Default is@NumberOfDigits (Digits.THIRTEEN) assumedpublic class IsbnGenerator{ public String generateNumber() { return “13-84356” + nextNumber(); }} Example Credit: Antonio Goncalves
    32. 32. QUALIFIED INJECTION OF RESOURCES@Path(”/items") @ManagedBeanpublic class ItemRestEndpoint { Here we inject the @Inject @NumberOfDigits(Digits.EIGHT) qualified private NumberGenerator numGen; beans, and require …} and profit@WebServlet(urlPatterns=”/itemServlet")public class ItemServlet { @Inject @NumberOfDigits(Digits.THIRTEEN) private NumberGenerator numGen; …} Example Credit: Antonio Goncalves
    33. 33. ALTERNATIVESAn alternative bean is one which must be specifically enabled for a particular deployment It replaces the managed or session bean for which it is an alternative May also completely replace it  all producers and observers defined on original bean are disabled for this deployment) Alternatives enabled in XML deployment descriptor
    34. 34. DEFINING AN ALTERNATIVE@Alternative Same API, different@ThirteenDigits @EightDigits implementationpublic class MockGenerator implementsNumberGenerator { public String generateNumber() { return ”MOCK- " + nextNumber(); }}
    35. 35. ENABLING AN ALTERNATIVE<beans> <alternatives> <class>com.acme.MockGenerator</class> <stereotype>com.acme.numbers.mock</stereotype> </alternatives></beans> Can also define a sterotype as an alternatives. Any stereotyped beans will be an alternative
    36. 36. STEREOT YPES We have common architectural “patterns” in our application, with recurring roles Capture the roles using stereotypes Stereotypes may declare other stereotypes  (Built-In example @Model)
    37. 37. STEREOT YPESA stereotype encapsulates any combination of: a default scope, and a set of interceptor bindings.A stereotype may also specify that: all beans with the stereotype have defaulted bean EL names all beans with the stereotype are alternatives
    38. 38. CREATING A STEREOT YPE@RequestScoped Scope@Named@Alternative@Stereotype Has a defaulted name@Retention(RUNTIME)@Target(TYPE)public @interface MyAlternativeAction{} All stereotyped beans become alternatives
    39. 39. USING A STEREOT YPE@MyAlternativeActionpublic class Hello { public String sayHello(String name) { return "hi " + name; }}
    40. 40. SCOPES AND CONTEXTSBuilt-in scopes:  Any servlet - @ApplicationScoped, @RequestScoped, @Sess ionScoped  JSF requests - @ConversationScoped  Dependent scope (Default): @DependentCustom scopes  A scope type is an annotation, can write your own context implementation and scope type annotation
    41. 41. SCOPES@SessionScopedpublic class Login { Session scoped private User user; public void login() { user = ...; } public User getUser() { return user; }}
    42. 42. SCOPESpublic class Printer { No coupling between @Inject Hello hello; scope and use of @Inject Login login; implementation public void printHello() { System.out.println( hello.sayHello( login.getUser().getName() ) ); }}
    43. 43. PRODUCER METHODSProducer methods allow control over the production of a bean where: the objects to be injected are not managed instances the concrete type of the objects to be injected may vary at runtime the objects require some custom initialization that is not performed by the bean constructor47 47 Pete Muir
    44. 44. PRODUCER METHODS@SessionScopedpublic class Login { private User user; public void login() { user = ...; } @Produces User getUser() { return user; }}
    45. 45. PRODUCER METHODSpublic class Printer { @Inject Hello hello; @Inject User user; Much better, no public void hello() { dependency on System.out.println( Login! hello.sayHello( user.getName() ) ); }}
    46. 46. PRODUCER FIELDSSimpler alternative to Producer methods Similar to@SessionScoped outjection inpublic class Login { Seam @Produces @LoggedIn @RequestScoped private User user; public void login() { user = ...; }}
    47. 47. JAVA EE RESOURCESpublic class PricesTopic { @Produces @Prices @Resource(name="java:global/env/jms/Prices") Topic pricesTopic;}public class UserDatabasePersistenceContext { @Produces @UserDatabase @PersistenceContext EntityManager userDatabase;}
    48. 48. EVENTSEvent producers raise events that are then delivered to event observers by the Context manager.  not only are event producers decoupled from observers; observers are completely decoupled from producers  observers can specify a combination of "selectors" to narrow the set of event notifications they will receive  observers can be notified immediately, or can specify that delivery of the event should be delayed until the end of the current transaction
    49. 49. Inject an instance of Event. Additional EVENTS qulaifiers can be specified to narrow the event consumers called. API type specified as a parameter on Eventpublic class Hello { @Inject @Any Event<Greeting> greeting; public void sayHello(String name) { new Greeting("hello " + name) ); }} “Fire” an event, the producer will be notified 53 Pete Muir
    50. 50. EVENTS Observer methods, take the APIpublic class Printer { type and additional qualifiers void onGreeting(@Observes Greeting greeting, @Default User user) { System.out.println(user + “ says “ + greeting); }} Additional parameters can be specified and will be injected by the container
    51. 51. CDI - EXTENSIBLE BY DESIGNMany community projects of extensions:  Seam 3, CODI, Cambridge Technology Partners Multiple projects merging to deliver a vendor - neutral common platform for extensions named DeltaSpike . Hosted on Apache. Works on Java EE 6 servers + + CDISource DeltaSpike
    52. 52. SEAM 3 MODULES• Solder • Mail DeltaSpike• Config • Validation• Social • Wicket• JMS • Catch• JCR JBoss • Remoting Developer• Security • REST Framework• I18N Drools SwitchYard • Faces jBPM Errai • Spring TBD Ecetera
    53. 53. SEAM 3 SPRING MODULE Seam3 - a library of CDI extensions Similar functionality to the Seam 2 Spring integration  With CDI specific undertones Will merge into Apache DeltaSpike
    54. 54. SPRING-CDI BRIDGEUse Java EE and Spring side by sideSpring Beans produced as Managed CDI beansSeam 3 Spring Module
    55. 55. INTEGRATING SPRING COMPONENTS INTO CDI Managed Managed Bean Bean Managed  Implemented as a Bean Standard CDI Extension  Spring contexts and • ApplicationContexts Spring beans are installed • Spring Beans as CDI beans * Can be bootstrapped or external  Implemented using the resource producer pattern
    56. 56. THE SPRING DAO <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource” destroy-method="close"> <property name="driverClassName" value="${jdbc.DriverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <context:property-placeholder location=""/> <context:component-scan base-package="demo.spring"/> <context:anntation-config/>
    57. 57. JSF / CDI BEAN Here we do not@Named @RequestScoped want to knowpublic class BooksBean { about Spring @Inject BooksJdbcDao booksDao; public List<String> getTitles() { return booksDao.listBookTitles(); }}
    58. 58. @SPRINGCONTEXT ANNOTATION1.) Bootstrapped By CDI Extension
    59. 59. SPRING BEAN PRODUCERApply the resource producer pattern for creatingSpring ApplicationContext CDI beans
    60. 60. SEAM3 SPRING MODULE DESIGN GOALS  Minimize changes to existing code  Non-intrusive approach  Highly customizable  Mirror similar capabilities
    61. 61. WHY? Reuse existing investments Integrate groups with various expertise Simplify integration of Spring and Java EE Ease migration of legacy Spring apps to Java EE 6
    62. 62. SEAM 3 SPRING MODULE FEATURES Integrating Spring components into CDI  Accessing Spring ApplicationContexts  created by the extension -or-  access AC’s created by Spring components (e.g. web ApplicationContext) Accessing CDI beans  exposing Spring beans as CDI beans
    63. 63. I need one ofthose widgets for a marketing T YPICAL DEVELOPER meeting in an hour. NIGHTMARE
    65. 65. Let’s get started
    66. 66. Demonstration of Forgeand Java EE Application
    67. 67. GETS YOU STARTEDHandles details, gives you perspective QUICKLY … and time HANDLES “GOTCHAS” ADDS & ACTIVATES TECH VIA PLUGINS
    71. 71. ARQUILLIAN
    73. 73.  Reference Application  7+ In-Depth Tutorials  tutorial 7+ Videos RESOURCES  55+ “Quickstarts”  6+ Articles and Whitepapers   Social Campaign  Google  221/  Twitter  @TheJBossWay  Facebook 
    74. 74.  Max Andersen  “See Context & Dependency Injection from Java EE 6 in Action”  dependency-injection-from-java-ee-6-in-action Pete Muir REFERENCES  “CDI in Action” Andrew Lee Rubinger  “The Death of Slow”  jboss-as7-death-of-the-slowBert Ertman  EJB 3.1  ertman Antonio Goncalves  “To inject or not to inject: CDI is the question”  -inject-or-not-to-inject-cdi-is-the- question
    75. 75. ENTERPRISEJAVAAPPLICATIONS Results of lots of choice, little guidance.
    76. 76. THE JBOSS WAYTeaches developers how to easily adopttechnologies within JBoss EAP 6• Webinar Series• Reference Application “TicketMonster”• 3 Reference Architectures• 55+ Quickstarts• 7+ In-Depth Tutorials• 6+ Articles and Whitepapers• 7+ Recorded Videos• Social Campaign with HowTos• Growing Set of Technical Blogs
    77. 77. JSF 2 HTML5 GWT<h:form id="bookingForm"> <form name="reg" id="reg” public class Stockwatcher <fieldset> <fieldset> implements EntryPoint { <p:input id="checkInDate” <legend>Register a user: private VerticalPanel mainPanel <h:inputText id="input” <div> private FlexTable stocksFlexTable <f:convertDateTime type= <label for="email">Email: private HorizontalPanel addPanel </h:inputText> <input type="email" private TextBox newSymbolText name="email" id="email" private Button addStockButton placeholder="Your Email” More Choice Struts SpringMVC Tapestry Wicket Flex Rails* … CDI, EJB, Spring Beans JPA, Hibernate * Ruby on Rails on JBoss via TorqueBox
    79. 79. SIMPLE ARCHITECTURE Native Mobile (Apache Cordova) User Front-end (POH5) Monitoring Admin Front-end Classic UI Mobile UI Dashboard (JSF, Forge) (GWT, Errai) ForgeBusiness Layer (CDI, EJB, JAX-RS) Scaffold Persistence (JPA)
    80. 80. PLAIN OLD HTML5 (POH5)
    81. 81. A MODERN SET OF TECHNOLOGIES JBoss Developer Studio 5 OpenShift - PaaS Java EE 6 - Maven - Jenkins Web Framework Kit 2 JBoss EAP 6 Spring Support TorqueBox Java EE 6 Red Hat Confidential - Do Not Distribute