• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Introduction to CDI and DI in Java EE 6
 

Introduction to CDI and DI in Java EE 6

on

  • 5,924 views

 

Statistics

Views

Total Views
5,924
Views on SlideShare
5,924
Embed Views
0

Actions

Likes
14
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • 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.http://showcase.richfaces.org/Key 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 bit.ly 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 Introduction to CDI and DI in Java EE 6 Presentation Transcript

  • Productive,LEARNING CDI Simple, Modern Ray Ploski Director, Developer Programs & Strategy JBoss, by Red Hat, Inc.
  • AGENDA Background Concepts Status & Roadmap
  • 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
  • GREAT !!!
  • J2EE #fail #fail EJB #fail
  • EJB 2.X SESSION BEAN
  • 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>
  • EJB 2.X CLIENT VIEW
  • J2EE #fail #fail EJB #fail
  • 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
  • Java EE 6
  • 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
  • EJB 3.1 SESSION BEAN OPTIONAL!
  • JAVA EE 6 DEPLOYMENT DESCRIPTOR
  • EJB 3.1 CLIENT VIEW@EJB BankLocal bank;public void makeDeposit(){ bank.deposit(2500.00, new Account(12345));}
  • 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
  • EASE OF USE IMPROVEMENTS Optional Local Interface Simplified Packaging EJB-Lite Portable JNDI Naming Simple Component Testing
  • 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
  • MANAGED BEANSContainer-managed POJOs with minimal requirementssupport a set of basic services  resource injection  lifecycle callbacks  interceptors
  • 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
  • AGENDA Background Concepts Status & Roadmap
  • Loose CouplingSTRONG TYPING
  • 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
  • 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; }}
  • 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") ); }}
  • 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
  • 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; }}
  • JSF PAGE<h:commandButton value=“Say Hello” action=“#{hello.sayHello}”/> Calling an action on a bean through EL
  • WHAT MAKES CDI UNIQUE? Standard Type SafeExtensible
  • 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
  • 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
  • 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
  • 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
  • DEFINING AN ALTERNATIVE@Alternative Same API, different@ThirteenDigits @EightDigits implementationpublic class MockGenerator implementsNumberGenerator { public String generateNumber() { return ”MOCK- " + nextNumber(); }}
  • 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
  • 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)
  • 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
  • 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
  • USING A STEREOT YPE@MyAlternativeActionpublic class Hello { public String sayHello(String name) { return "hi " + name; }}
  • 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
  • SCOPES@SessionScopedpublic class Login { Session scoped private User user; public void login() { user = ...; } public User getUser() { return user; }}
  • 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() ) ); }}
  • 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
  • PRODUCER METHODS@SessionScopedpublic class Login { private User user; public void login() { user = ...; } @Produces User getUser() { return user; }}
  • 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() ) ); }}
  • 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 = ...; }}
  • JAVA EE RESOURCESpublic class PricesTopic { @Produces @Prices @Resource(name="java:global/env/jms/Prices") Topic pricesTopic;}public class UserDatabasePersistenceContext { @Produces @UserDatabase @PersistenceContext EntityManager userDatabase;}
  • 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
  • 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) { greeting.fire( new Greeting("hello " + name) ); }} “Fire” an event, the producer will be notified 53 Pete Muir
  • 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
  • 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
  • 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
  • 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
  • SPRING-CDI BRIDGEUse Java EE and Spring side by sideSpring Beans produced as Managed CDI beansSeam 3 Spring Module
  • 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
  • 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="classpath:jdbc.properties"/> <context:component-scan base-package="demo.spring"/> <context:anntation-config/>
  • 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(); }}
  • @SPRINGCONTEXT ANNOTATION1.) Bootstrapped By CDI Extension
  • SPRING BEAN PRODUCERApply the resource producer pattern for creatingSpring ApplicationContext CDI beans
  • SEAM3 SPRING MODULE DESIGN GOALS  Minimize changes to existing code  Non-intrusive approach  Highly customizable  Mirror similar capabilities
  • 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
  • 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
  • I need one ofthose widgets for a marketing T YPICAL DEVELOPER meeting in an hour. NIGHTMARE
  • CARVE OUT A PROJECTWORK IT INTO SHAPE
  • Let’s get started
  • Demonstration of Forgeand Java EE Application
  • GETS YOU STARTEDHandles details, gives you perspective QUICKLY … and time HANDLES “GOTCHAS” ADDS & ACTIVATES TECH VIA PLUGINS
  • TESTING JAVA EE USED TO BE DIFFICULT
  • MANY STEPS REQUIRED FOR MODIFYING CODE PRODUCTIVELY
  • ARQUILLIAN REMOVES THE STEPS
  • ARQUILLIAN
  • ARQUILLIAN REMOVES THE STEPS
  •  Reference Application  https://github.com/jboss/ticket-monster 7+ In-Depth Tutorials  https://github.com/jboss/ticket-monster- tutorial 7+ Videos RESOURCES  http://jboss.org/developer/videos 55+ “Quickstarts”  https://github.com/jbossas/quickstart 6+ Articles and Whitepapers  http://jboss.org/developer/articles.html  http://www.howtojboss.com Social Campaign  Google  https://plus.google.com/b/114105440952945834 221/  Twitter  @TheJBossWay  Facebook  https://www.facebook.com/jboss
  •  Max Andersen  “See Context & Dependency Injection from Java EE 6 in Action”  http://www.slideshare.net/maxandersen/see-context- dependency-injection-from-java-ee-6-in-action Pete Muir REFERENCES  “CDI in Action” Andrew Lee Rubinger  “The Death of Slow”  http://www.slideshare.net/ALRubinger/devoxx-2011- jboss-as7-death-of-the-slowBert Ertman  EJB 3.1  http://www.slideshare.net/stephanj/ejb-31-by-bert- ertman Antonio Goncalves  “To inject or not to inject: CDI is the question”  http://www.slideshare.net/agoncal/to -inject-or-not-to-inject-cdi-is-the- question
  • ENTERPRISEJAVAAPPLICATIONS Results of lots of choice, little guidance.
  • 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
  • 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
  • TICKET MONSTERREFERENCE APPLICATION
  • 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)
  • PLAIN OLD HTML5 (POH5)
  • 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