1. Productive,
LEARNING CDI Simple,
Modern
Ray Ploski
Director, Developer Programs & Strategy
JBoss, by Red Hat, Inc.
2. AGENDA
Background
Concepts
Status & Roadmap
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
11. 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
13. JAVA EE 6
The EE 6 web profile removes most of
the “cruft” that has developed over
the 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
16. EJB 3.1 CLIENT VIEW
@EJB BankLocal bank;
public void makeDeposit()
{
bank.deposit(2500.00, new Account(12345));
}
17. 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
18. EASE OF USE IMPROVEMENTS
Optional Local Interface
Simplified Packaging
EJB-Lite
Portable JNDI Naming
Simple Component Testing
19. 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
20. MANAGED BEANS
Container-managed POJOs with
minimal requirements
support a set of basic services
resource injection
lifecycle callbacks
interceptors
21. 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
22. AGENDA
Background
Concepts
Status & Roadmap
26. DEPENDENCY INJECTION
IN TWO PARTS
DI (@Inject) CDI
JSR 330 JSR 299
javax.inject javax.enterprise.context
@Inject Alternatives
@Named Producers
@Singleton Scopes
@Qualifier Stereotypes
@Scope Decorators
Extensions
27. SIMPLE EXAMPLE
public class Hello { Any Managed Bean
public String sayHello(String name) {
can use these
return "hello" + name;
} services
}
@Stateless So can EJBs
public class Hello {
public String sayHello(String name) {
return "hello" + name;
}
}
28. SIMPLE EXAMPLE
@Inject defines an
public class Printer { injection point.
@Inject Hello hello;
@Default qualifier is
assumed
public void printHello() {
System.out.println( hello.sayHello("world") );
}
}
29. CONSTRUCTOR INJECTION
public 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
30. 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 name
public class Hello {
public String sayHello(String name) {
return "hello" + name;
}
}
33. 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
34. 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) assumed
public class IsbnGenerator{
public String generateNumber() {
return “13-84356” + nextNumber();
}
}
Example Credit: Antonio Goncalves
35. QUALIFIED INJECTION OF
RESOURCES
@Path(”/items") @ManagedBean
public 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
36. 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
37. DEFINING AN ALTERNATIVE
@Alternative Same API, different
@ThirteenDigits @EightDigits implementation
public class MockGenerator implements
NumberGenerator {
public String generateNumber() {
return ”MOCK- " + nextNumber();
}
}
38. 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
39. 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)
40. 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
41. 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
42. USING A STEREOT YPE
@MyAlternativeAction
public class Hello {
public String sayHello(String name) {
return "hi " + name;
}
}
43. 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
45. SCOPES
public 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() ) );
}
}
46. 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 constructor
47
47 Pete Muir
48. PRODUCER METHODS
public class Printer {
@Inject Hello hello;
@Inject User user; Much better, no
public void hello() { dependency on
System.out.println( Login!
hello.sayHello( user.getName() ) );
}
}
49. PRODUCER FIELDS
Simpler alternative to Producer methods
Similar to
@SessionScoped outjection in
public class Login {
Seam
@Produces @LoggedIn @RequestScoped
private User user;
public void login() {
user = ...;
}
}
50. JAVA EE RESOURCES
public class PricesTopic {
@Produces @Prices
@Resource(name="java:global/env/jms/Prices")
Topic pricesTopic;
}
public class UserDatabasePersistenceContext {
@Produces @UserDatabase
@PersistenceContext
EntityManager userDatabase;
}
51. 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
52. Inject an instance of Event. Additional
EVENTS qulaifiers can be specified to narrow the
event consumers called. API type
specified as a parameter on Event
public 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
53. EVENTS
Observer methods, take the API
public 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
54. 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
56. 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
57. SPRING-CDI BRIDGE
Use Java EE and Spring side by side
Spring Beans produced as Managed CDI
beans
Seam 3 Spring Module
58. 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
59. 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/>
60. JSF / CDI BEAN
Here we do not
@Named @RequestScoped
want to know
public class BooksBean { about Spring
@Inject BooksJdbcDao booksDao;
public List<String> getTitles() {
return booksDao.listBookTitles();
}
}
61. @SPRINGCONTEXT
ANNOTATION
1.) Bootstrapped
By CDI Extension
62. SPRING BEAN PRODUCER
Apply the resource producer pattern for creating
Spring ApplicationContext CDI beans
63. SEAM3 SPRING MODULE DESIGN GOALS
Minimize changes to existing code
Non-intrusive approach
Highly customizable
Mirror similar capabilities
64. 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
65. 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
66. I need one of
those widgets for
a marketing
T YPICAL DEVELOPER
meeting in an
hour.
NIGHTMARE
78. 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
80. THE JBOSS WAY
Teaches developers how to easily adopt
technologies 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
81. 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
85. 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
Notas do Editor
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.