cdi deep dive

Download CDI Deep Dive

Post on 08-May-2015

1.142 views

Category:

Documents

2 download

Embed Size (px)

DESCRIPTION

Speaker: Jens Schumann (eig. Mark Struberg) W-JAX 2012

TRANSCRIPT

  • 1.Jens Schumann open knowledge GmbHMark Struberg / INSO, TU ViennaCDI Deep Dive

2. About Mark struberg@apache.org http://github.com/struberg http://people.apache.org/~struberg freelancer, programmer since 20 years elected Apache Software Foundation member Apache OpenWebBeans PMC + PMC andcommitter in other ASF projects: MyFaces,BVAL, OpenJPA, Maven, DeltaSpike, ... CDI EG member 3. About me 4. How the ASF works Non profit Organization Contributors Committers PMC member(Project Management Committee) ASF member ASF board of directors 5. Agenda Short JSR-299 Overview The Container Lifecycle Behaviour Change wo Extensions:Alternatives, Specializes, Interceptors Extension basics Sample: Dynamic Interceptor Sample: @ViewScoped Context 6. Agenda Short JSR-299 Overview The Container Lifecycle Behaviour Change wo Extensions:Alternatives, Specializes, Interceptors Extension basics Sample: Dynamic Interceptor Sample: @ViewScoped Context 7. JSR-299 Overview Contexts and Dependency Injection forthe Java EE platform (CDI) Component Model for Java (SE & EE) Originally designed for EE but alsousable for standalone applications Based on JSR-330 8. CDI Features Typesafe Dependency Injection Interceptors Decorators Events SPI for implementing PortableExtensions Unified EL integration 9. Available Implementations JBoss Weld (RI) Apache OpenWebBeans Resin CanDI maybe Spring in the future? 10. A small Example Supply META-INF/beans.xml marker file Create a MailService implementation@ApplicationScopedpublic class MyMailService implements MailService {private @Inject User usr;public send(String from, String to,String body) {}} 11. A small Example We also need a User bean@SessionScoped@Namedpublic class User {public String getName() {..}..} 12. A small Example Injecting the Bean @RequestScoped @Named(mailForm) public class MailFormular { private @Inject MailService mailSvc; private @Inject User usr; public String sendMail() { mailSvc.send(usr.getEmail(),other, sometext); return successPage; } } 13. A small Example Use the beans via Expression Language 14. Agenda Short JSR-299 Overview The Container Lifecycle Behaviour Change wo Extensions:Alternatives, Specializes, Interceptors Extension basics Sample: Dynamic Interceptor Sample: @ViewScoped Context 15. Terms Managed Bean The term Managed Bean means a JavaClass and all its rules to createcontextual instances of that bean. Interface Bean extends Contextual Managed Beans in JSR-299 and JSR-346 doesnt mean JavaBeans! 16. Terms Contextual Instance The term Contextual Instance means aJava instance created with the rules ofthe Managed Bean Bean Contextual Instances usually dont getinjected directly! 17. Terms Contextual Reference The term Contextual Reference meansa proxy for a Contextual Instance. Proxies will automatically be created forinjecting @NormalScope beans. 18. How Proxies work Interface Proxies vs Class Proxies Generated subclasses which overloadall non-private, non-static methods. public doSomething(param) { getInstance().doSomething(param); } private T getInstance() { beanManager.getContext().get(...); } Can contain Interceptor logic 19. Why use Proxies Container-Behaviour: Interceptors,Decorators scope-differences - this happens e.g. ifa @SessionScoped User gets injectedinto a @ApplicationScoped MailService. Passivation of non-serializablecontextual instances (via its contextualreference) 20. LifeCycle - The big picture Creating the meta information at startup Classpath Scanning and creating ManagedBeans meta-information Contextual Instance creation at runtime Based on the Managed Beans, the Contextwill maintain the instances Well defined contextual instancetermination 21. homework: some hacking Create a new project from a mavenarchetype $> mvn archetype:generate -DarchetypeCatalog= http://people.apache.org/~jakobk/m2_archetypes_103_release Select myfaces-archetype-codi-jsf20 start the web application in jetty $> mvn clean install -PjettyConfig jetty:run-exploded $> tree src 22. Behaviour Change withoutCDI Extensions 23. Agenda Short JSR-299 Overview The Container Lifecycle Behaviour Change wo Extensions:Alternatives, Specializes, Interceptors Extension basics Sample: Dynamic Interceptor Sample: @ViewScoped Context Apache DeltaSpike JSR-346 (CDI-1.1) Early Draft Features 24. Interceptors An Interceptor decouples technicalconcerns from business logic Applying cross cutting concerns tobeans JSR-299 allows you to write your owninterceptors Interceptors are treated as being@Dependent to the intercepted class 25. Interceptor usage Interceptor annotations can be appliedon method or class level @ApplicationScoped public class UserService { @Transactional public storeUser(User u) { ... } } 26. InterceptorBinding Type InterceptorBindings are used to identifywhich Interceptors should be applied toa bean @InterceptorBinding @Retention(RetentionPolicy.RUNTIME) @Target( { ElementType.TYPE,ElementType.METHOD }) public @interface Transactional {} 27. The Interceptor Impl@Interceptor @Transactionalpublic class TransactionalInterceptor {private @Inject EntityManager em;@AroundInvokepublic Object invoke(InvocationContext ctx) throws Exception { ...return ctx.proceed(); ...}} 28. The Interceptor Implpublic Object invoke(InvocationContext ctx) throws Exception {EntityTransaction t = em.getTransaction();try {if(!t.isActive()) { t.begin() };return context.proceed();} catch(Exception e) {// .. rollback} finally {// commit if started and not rolled back}} 29. Enabling Interceptors Interceptors need to be enabledmanually in beans.xml You can define the order in whichmultiple Interceptors stack org.mycomp.Securedorg.mycomp.Transactional 30. @Specializes Replaces the Managed Bean of a superclass Bean must extends the superclass possible to specialize Producer Methods or even EJBs: @Stateless public class UserSvcFacade implements UserSvc{ ... } @Stateless @Mock @Specializes public class MockUserSvcFacade extends UserSvcFacade{ ... } 31. @Alternative Swap Implementations for differentinstallations Kind of an optional override of a bean @Alternative public class MockMailService implements MailService { ... Disabled by default org.mycomp.MockMailService... 32. Alternatives / Interceptors Pitfalls Per CDI-1.0 only active for the BDA(Bean Definition Archive) That will officially be changed in CDI-1.1see https://issues.jboss.org/browse/CDI-18 OpenWebBeans always used globalenablement Weld now globally enables them ifdefined in WEB-INF/beans.xml 33. Typesafe Configuration Config without properties or XML files Just create an Interface or defaultconfig class public interface MyConfig{String getJdbcUrl(); } Later just implement, @Specializes,@Alternative, @ProjectStageActivated,@ExpressionActivated your config impl. 34. Events Observer/Observable pattern Inject a Event Source@Injectprivate Event loginEvent;private @Inject User user;loginEvent.fire(new UserLoggedIn(user) ); 35. Events Observer/Observable pattern Consume an Event void onLogin(@Observes UserLoggedIn ule) { ule.getUser().getName; ... } Attention: Use qualified events dont use private observer methods! 36. @Typed Defines the Java Type which should be usedfor that bean Possible to disable a bean with @Typed()to prevent AmbiguousResolutionExceptions@Typed() // basically disables this Beanpublic class MenuItem implementsSerializable { } handy for subclasses which should NOTconflict with their parent class types 37. Explicitly @Typed@ApplicationScopedpublic class TrackReadOnlyService {public Track readTrack(int id) {..}}@Typed(TrackReadWriteService.class)@ApplicationScopedpublic class TrackReadWriteServiceextends TrackReadOnlyService {public void writeTrack(Track t) {..}} 38. Portable Extensions 39. Agenda Short JSR-299 Overview The Container Lifecycle Behaviour Change wo Extensions:Alternatives, Specializes, Interceptors Extension basics Sample: Dynamic Interceptor Sample: @ViewScoped Context 40. Writing own Extensions CDI Extensions are portable and easy to write! Are activated by simply droppingthem into the classpath CDI Extensions are based onjava.util.ServiceLoader Mechanism 41. Extension Basics Extensions will get loaded by theBeanManager Each BeanManager gets its own Extensioninstance During the boot, the BeanManager sendsLifecycle Events to the Extensions Attention:strictly distinguish between boot and runtime! 42. Extension Lifecycle Events Extensions picked up and instantiated atContainer startup Container sends system events which allExtensions can @Observes: BeforeBeanDiscovery ProcessAnnotatedType ProcessInjectionTarget AfterBeanDiscovery AfterDeploymentValidation BeforeShutdown 43. New CDI-1.1 Lifecycle Events ProcessModule allows modifying Alternatives,Interceptors and Decorators ProcessSyntheticAnnotatedType ProcessInjectionPoint Currently under discussion:ProcessAnnotatedType with@HasAnnotation(Annotation[]) 44. Register the Extension Extensions need to get registered forthe ServiceLoader Create a file META-INF/services/javax.enterprise.inject.spi.Extension Simply write the Extensions classnameinto it com.mycomp.MyFirstCdiExtension 45. The AnnotatedType Provides access to all important reflectionbased information Can be modified via CDI Extensions inProcessAnnotatedType Each scanned Class is one AnnotatedType @since CDI-1.1:BeforeBeanDiscovery#addAnnotatedType Typically changed in ProcessAnnotatedType 46. Popular Extensions Apache MyFaces CODI http://myfaces.apache.org/extensions/cdi JBoss Seam3 http://seamframework.org/Seam3 CDISource https://github.com/cdisource Apache DeltaSpike https://cwiki.apache.org/confluence/display/DeltaSpike/Index http://incubator.apache.org/deltaspike 47. Vetoing Beans ProcessAnnotatedType#veto() Can be used to dynamically disable aBean DeltaSpike#Exclude 48. DeltaSpike @Exclude Used to disable bean depending on acertain situation @Exclude() @Exclude(ifProjectStage=ProjectStage.Development.class) @Exclude(exceptIfProjectStage=ProjectStage.Development.class) @Exclude(onE