Designing Java EE Applications in the Age of CDI
Post on 08-May-2015
2094 Views
Preview:
DESCRIPTION
Transcript
Designing Java EE Applications in the Age of CDI
Michael Nascimento SantosMichel Graciano
JavaOne 2012
04/12/2012 Designing Java EE Applications in the Age of CDI 22
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 33
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 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 5
Terminology
• JSR 299 - CDIContexts and Dependency Injection for the Java
EE platform
• WeldJSR-299 Reference Implementation
04/12/2012 Designing Java EE Applications in the Age of CDI 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 7
@InjectGreeting greeting;@InjectGreeting greeting;
CDI crash-course
• Beans can be injected using @Inject• Injected beans can be filtered and/or
disambiguated using @Qualifier
04/12/2012 Designing Java EE Applications in the Age of CDI 8
@Informal@InjectGreeting greeting;
@Informal@InjectGreeting greeting;
CDI crash-course
• Beans can be injected using @Inject• Injected beans can be filtered and/or
disambiguated using @Qualifier
04/12/2012 Designing Java EE Applications in the Age of CDI #ageofcdi 9
@Qualifier@Retention(RUNTIME)@Target({METHOD, FIELD, PARAMETER, TYPE})public @interface Informal {}
@Qualifier@Retention(RUNTIME)@Target({METHOD, FIELD, PARAMETER, TYPE})public @interface Informal {}
CDI crash-course
04/12/2012 Designing Java EE Applications in the Age of CDI 10
CDI crash-course
• Beans can be named using @Named
@Named(“pageModel”)public class PageModel { public getName() { ... }}
@Named(“pageModel”)public class PageModel { public getName() { ... }}
<h:body> #{pageModel.name}</h:body>
<h:body> #{pageModel.name}</h:body>
04/12/2012 Designing Java EE Applications in the Age of CDI 11
public class Shop { @Produces PaymentProcessor getPaymentProcessor() { ... }
@Produces List<Product> getProducts() { ... }}
public class Shop { @Produces PaymentProcessor getPaymentProcessor() { ... }
@Produces List<Product> getProducts() { ... }}
CDI crash-course
• Beans with special initialization can be constructed using producers
04/12/2012 Designing Java EE Applications in the Age of CDI 12
public class Shop { @Produces @ApplicationScoped @Catalog @Named("catalog") List<Product> getProducts() { ... }}
public class Shop { @Produces @ApplicationScoped @Catalog @Named("catalog") List<Product> getProducts() { ... }}
CDI crash-course
• Beans with special initialization can be constructed using producers
04/12/2012 Designing Java EE Applications in the Age of CDI 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 14
But what's the point of CDI anyway?
04/12/2012 Designing Java EE Applications in the Age of CDI 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 16
Clean scope combination
• Scopes determine the bean instances lifecycle and can be safely combined as needed
@ApplicationScopedpublic class System implements Serializable { @Inject User user; ...}
@ApplicationScopedpublic class System implements Serializable { @Inject User user; ...}
@SessionScopedpublic class User implements Serializable { ... }
@SessionScopedpublic class User implements Serializable { ... }
04/12/2012 Designing Java EE Applications in the Age of CDI 17
Custom scopes
• SeamRenderScoped
• MyFaces CODI@ConversationScoped@WindowScoped@ViewAccessScoped
• Apache DeltaSpike@TransactionScoped
04/12/2012 Designing Java EE Applications in the Age of CDI 18
public void afterDocumentUpdate(@Observes @Updated Document document) { ... }
public void afterDocumentUpdate(@Observes @Updated Document document) { ... }
public void onAnyDocumentEvent(@Observes Document document) { ... }public void onAnyDocumentEvent(@Observes Document document) { ... }
Event system
• Loose-decoupled event producers from consumers by the event notifications model
• Events can be filtered using qualifiers
04/12/2012 Designing Java EE Applications in the Age of CDI 19
@Inject @Any Event<Document> event;
...
public void someMethod() { event.fire(document);}
@Inject @Any Event<Document> event;
...
public void someMethod() { event.fire(document);}
Event system
• Loose-decoupled event producers from consumers by the event notifications model
• Events can be filtered using qualifiers
04/12/2012 Designing Java EE Applications in the Age of CDI 20
@Inject @Updated Event<Document> event;
...
public void someMethod() { event.fire(document);}
@Inject @Updated Event<Document> event;
...
public void someMethod() { event.fire(document);}
Event system
• Loose-decoupled event producers from consumers by the event notifications model
• Events can be filtered using qualifiers
04/12/2012 Designing Java EE Applications in the Age of CDI 21
Event system
• Conditional observersIF_EXISTSALWAYS
public void afterDocumentUpdate(@Observes(receive=IF_EXISTS)@Updated Document document) { ... }
public void afterDocumentUpdate(@Observes(receive=IF_EXISTS)@Updated Document document) { ... }
04/12/2012 Designing Java EE Applications in the Age of CDI 22
Event system
• Transactional observersIN_PROGRESS,BEFORE_COMPLETION,AFTER_COMPLETION,AFTER_FAILURE,AFTER_SUCCESS
public void afterDocumentUpdate(@Observes(during=AFTER_SUCCESS)@Updated Document document) { ... }
public void afterDocumentUpdate(@Observes(during=AFTER_SUCCESS)@Updated Document document) { ... }
04/12/2012 Designing Java EE Applications in the Age of CDI 23
AOP without interfaces
• Interceptors decouple technical concerns from business logicOrthogonal to the application and type system
• Decorators allow business concerns to be compartmentalized using the interceptor conceptAttached to a Java type, aware of business
semantics
• ConfigurableEnabled and ordered at beans.xml file, allowing
different behaviours for different environments
04/12/2012 Designing Java EE Applications in the Age of CDI 24
@Inherited@InterceptorBinding@Target({TYPE, METHOD})@Retention(RUNTIME)public @interface Secure {}
@Inherited@InterceptorBinding@Target({TYPE, METHOD})@Retention(RUNTIME)public @interface Secure {}
Interceptors
04/12/2012 Designing Java EE Applications in the Age of CDI 25
@Secure@Interceptorpublic class SecurityInterceptor { @AroundInvoke public Object manageSecurity(InvocationContext ctx) throws Exception { // manage security... return ctx.proceed(); }}
@Secure@Interceptorpublic class SecurityInterceptor { @AroundInvoke public Object manageSecurity(InvocationContext ctx) throws Exception { // manage security... return ctx.proceed(); }}
Interceptors
04/12/2012 Designing Java EE Applications in the Age of CDI 26
@Securepublic class System { ...}
@Securepublic class System { ...}
public class ShoppingCart { @Secure public void placeOrder() { ... }}
public class ShoppingCart { @Secure public void placeOrder() { ... }}
Interceptors
04/12/2012 Designing Java EE Applications in the Age of CDI 27
Decorators
@Decoratorclass TimestampLogger implements Logger { @Inject @Delegate @Any Logger logger;
@Override void log(String message) { logger.log( timestamp() + ": " + message ); } ...}
@Decoratorclass TimestampLogger implements Logger { @Inject @Delegate @Any Logger logger;
@Override void log(String message) { logger.log( timestamp() + ": " + message ); } ...}
04/12/2012 Designing Java EE Applications in the Age of CDI 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 29
Access to injection point
@ProducesLogger createLogger(InjectionPoint ip) { return Logger.getLogger( ip.getMember().getDeclaringClass(). getName());}
@ProducesLogger createLogger(InjectionPoint ip) { return Logger.getLogger( ip.getMember().getDeclaringClass(). getName());}
public class SomeClass { @Inject Logger logger; ...}
public class SomeClass { @Inject Logger logger; ...}
04/12/2012 Designing Java EE Applications in the Age of CDI 30
Portable extensions
<T> void processAnnotatedType(@Observes final ProcessAnnotatedType<T> pat) { final AnnotatedTypeBuilder builder = new AnnotatedTypeBuilder(). readFromType(pat.getAnnotatedType(), true).addToClass(NamedLiteral.INSTANCE);
pat.setAnnotatedType(builder.create());}
<T> void processAnnotatedType(@Observes final ProcessAnnotatedType<T> pat) { final AnnotatedTypeBuilder builder = new AnnotatedTypeBuilder(). readFromType(pat.getAnnotatedType(), true).addToClass(NamedLiteral.INSTANCE);
pat.setAnnotatedType(builder.create());}
04/12/2012 Designing Java EE Applications in the Age of CDI 31
Portable extensions
<X> void processInjectionTarget(@Observes ProcessInjectionTarget<X> pit) { for (InjectionPoint ip : pit.getInjectionTarget(). getInjectionPoints()) { ... }}
<X> void processInjectionTarget(@Observes ProcessInjectionTarget<X> pit) { for (InjectionPoint ip : pit.getInjectionTarget(). getInjectionPoints()) { ... }}
04/12/2012 Designing Java EE Applications in the Age of CDI 32
Putting it all together
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
Named queries are not safe
04/12/2012 Designing Java EE Applications in the Age of CDI 35
Typesafe @TypedQuery
04/12/2012 Designing Java EE Applications in the Age of CDI 36
Typesafe @TypedQuery
-------------------------------------------------------------COMPILATION ERROR : -------------------------------------------------------------and returns false.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.2 errors -------------------------------------------------------------
-------------------------------------------------------------COMPILATION ERROR : -------------------------------------------------------------and returns false.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.2 errors -------------------------------------------------------------
04/12/2012 Designing Java EE Applications in the Age of CDI 37
Demo
04/12/2012 Designing Java EE Applications in the Age of CDI 38
Features used
• CDIDependency injectionProducer methodsAccess to the injection point
• Annotation processors
04/12/2012 Designing Java EE Applications in the Age of CDI 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 40
Auto-generated MBeans
04/12/2012 Designing Java EE Applications in the Age of CDI 41
Demo
04/12/2012 Designing Java EE Applications in the Age of CDI 42
Features used
• CDIDependency injectionProducer fieldsPortable extensionsCallback eventsInterceptors
• JMXMXBeanDynamicMBean
04/12/2012 Designing Java EE Applications in the Age of CDI #ageofcdi 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
12/04/12 Designing Java EE Applications in the Age of CDI 44
Q&A
Michael N. Santos | @mr__mhttp://blog.michaelnascimento.com.br/
michael.nascimento@tecsinapse.com.br
Michel Graciano | @mgracianohttp://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
Thank you
Michael N. Santos | @mr__mhttp://blog.michaelnascimento.com.br/
michael.nascimento@tecsinapse.com.br
Michel Graciano | @mgracianohttp://www.summa.com.br/
michel.graciano@summa.com.br
https://github.com/mgraciano/javaone-2012/
top related