CDI provides features for dependency injection, events, interceptors, and extensions in Java EE applications. The presentation discusses CDI scopes, qualifiers, producers, events, interceptors, decorators, access to injection points, and portable extensions. It demonstrates how to generate JMX MBeans from CDI metadata and use CDI with JMX. The presenters encourage designing new Java EE applications using CDI's unique capabilities.
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
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
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