designing java ee applications in the age of cdi

45
Designing Java EE Applications in the Age of CDI Michael Nascimento Santos Michel Graciano JavaOne 2012

Upload: michel-graciano

Post on 08-May-2015

2.094 views

Category:

Technology


4 download

DESCRIPTION

Even though CDI has been available since the end of 2009, most people still do not realize its full power and the possibilities it brings. Attend this session to understand which CDI features make it excel in comparison with other dependency-injection-based solutions and see how they can be used to design flexible applications and frameworks that will stand the test of time.

TRANSCRIPT

Page 1: Designing Java EE Applications in the Age of CDI

Designing Java EE Applications in the Age of CDI

Michael Nascimento SantosMichel Graciano

JavaOne 2012

Page 2: Designing Java EE Applications in the Age of CDI

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

Page 3: Designing Java EE Applications in the Age of CDI

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

Page 4: Designing Java EE Applications in the Age of CDI

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

Page 5: Designing Java EE Applications in the Age of CDI

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

Page 6: Designing Java EE Applications in the Age of CDI

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

Page 7: Designing Java EE Applications in the Age of CDI

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

Page 8: Designing Java EE Applications in the Age of CDI

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

Page 9: Designing Java EE Applications in the Age of CDI

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

Page 10: Designing Java EE Applications in the Age of CDI

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>

Page 11: Designing Java EE Applications in the Age of CDI

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

Page 12: Designing Java EE Applications in the Age of CDI

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

Page 13: Designing Java EE Applications in the Age of CDI

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

Page 14: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 14

But what's the point of CDI anyway?

Page 15: Designing Java EE Applications in the Age of CDI

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

Page 16: Designing Java EE Applications in the Age of CDI

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 { ... }

Page 17: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 17

Custom scopes

• SeamRenderScoped

• MyFaces CODI@ConversationScoped@WindowScoped@ViewAccessScoped

• Apache DeltaSpike@TransactionScoped

Page 18: Designing Java EE Applications in the Age of CDI

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

Page 19: Designing Java EE Applications in the Age of CDI

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

Page 20: Designing Java EE Applications in the Age of CDI

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

Page 21: Designing Java EE Applications in the Age of CDI

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) { ... }

Page 22: Designing Java EE Applications in the Age of CDI

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) { ... }

Page 23: Designing Java EE Applications in the Age of CDI

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

Page 24: Designing Java EE Applications in the Age of CDI

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

Page 25: Designing Java EE Applications in the Age of CDI

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

Page 26: Designing Java EE Applications in the Age of CDI

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

Page 27: Designing Java EE Applications in the Age of CDI

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 ); } ...}

Page 28: Designing Java EE Applications in the Age of CDI

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

Page 29: Designing Java EE Applications in the Age of CDI

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; ...}

Page 30: Designing Java EE Applications in the Age of CDI

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());}

Page 31: Designing Java EE Applications in the Age of CDI

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()) { ... }}

Page 32: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 32

Putting it all together

Page 33: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 33

Named queries are not safe

Page 34: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 34

Named queries are not safe

Page 35: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 35

Typesafe @TypedQuery

Page 36: Designing Java EE Applications in the Age of CDI

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 -------------------------------------------------------------

Page 37: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 37

Demo

Page 38: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 38

Features used

• CDIDependency injectionProducer methodsAccess to the injection point

• Annotation processors

Page 39: Designing Java EE Applications in the Age of CDI

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

Page 40: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 40

Auto-generated MBeans

Page 41: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 41

Demo

Page 42: Designing Java EE Applications in the Age of CDI

04/12/2012 Designing Java EE Applications in the Age of CDI 42

Features used

• CDIDependency injectionProducer fieldsPortable extensionsCallback eventsInterceptors

• JMXMXBeanDynamicMBean

Page 43: Designing Java EE Applications in the Age of CDI

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

Page 44: Designing Java EE Applications in the Age of CDI

12/04/12 Designing Java EE Applications in the Age of CDI 44

Q&A

Michael N. Santos | @mr__mhttp://blog.michaelnascimento.com.br/

[email protected]

Michel Graciano | @mgracianohttp://www.summa.com.br/

[email protected]

https://github.com/mgraciano/javaone-2012/

Page 45: Designing Java EE Applications in the Age of CDI

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/

[email protected]

Michel Graciano | @mgracianohttp://www.summa.com.br/

[email protected]

https://github.com/mgraciano/javaone-2012/