SlideShare a Scribd company logo
1 of 58
Download to read offline
@antoine_sd#CDIUni
CDI University
@antoine_sd
Red Hat, http://cdi-spec.org
CDI specification leader
@antoine_sd#CDIUni
Antoine Sabot-Durand
•Senior Software Developer @Red Hat
!
•Java & OSS :
•CDI co-spec lead
•CDI eco-system development
•Tech Lead on Agorava
!
•@antoine_sd
•@cdispec
@YourTwitterHandle#DVXFR14{session hashtag} @antoine_sd#CDIUni
CDI basics
@antoine_sd#CDIUni
•CDI is a lot of things
•Java EE IoC standard also working on Java SE
•Context management
•Observer pattern included
•The « cement » between most Java EE spec
•An evolution engine for Java EE thanks to portable extensions
•All of this based on java strong typing
Context & Dependency Injection
@antoine_sd#CDIUni
CDI history & actual state
•Main milestone :
•December 2009 : CDI 1.0
•June 2013 : CDI 1.1
•April 2014 : CDI 1.2
•Summer 2014 : CDI 2.0 development starting
•Implementations :
•JBoss Weld (RI) : WildFly, JBoss EAP, Glassfish, Weblogic
•Apache OpenWebBeans : TomEE, Websphere
•Check http://cdi-spec.org
@antoine_sd#CDIUni
CDI activated by default in Java EE 7
•In Java EE 6, you must add a beans.xml file to your
archive
•No need to in Java EE 7 but you can still to have an
explicit activation (behave differently)
beans.xml
@antoine_sd#CDIUni
Bean
•In Java EE 6 everything is a Managed Bean
•Managed beans are basic components
•They are managed by the container
•They all have a lifecycle
•They can be intercepted (AOP)
•They can be injected
•Accessible from outside CDI code.
@antoine_sd#CDIUni
Dependency Injection
@Inject
@antoine_sd#CDIUni
public class HelloService {!
    public String hello() {!
        return "Hello World!";!
    }!
}
Dependency Injection
@antoine_sd#CDIUni
public class MyBean {!
!
    private HelloService service;!
!
    @Inject!
    public MyBean(HelloService service) {!
        this.service = service;!
    }!
    public void displayHello() {!
        display( service.hello();!
    }!
}
Dependency Injection in constructor
@antoine_sd#CDIUni
public class MyBean {!
!
    private HelloService service;!
!
    @Inject!
    public void setService(HelloService service) {!
        this.service = service;!
    }!
    public void displayHello() {!
        display( service.hello();!
    }!
}
Dependency Injection in setter
@antoine_sd#CDIUni
public class MyBean {!
!
    @Inject HelloService service;!
!
    public void displayHello() {!
        display( service.hello();!
    }!
}
Dependency Injection in field
@antoine_sd#CDIUni
public interface HelloService {!
    public String hello();!
}!
public class FrenchHelloService implements HelloService {!
    public String hello() {!
        return "Bonjour tout le monde!";!
    }!
}!
public class EnglishHelloService implements HelloService {!
    public String hello() {!
        return "Hello World!";!
    }!
}
Qualifiers
@antoine_sd#CDIUni
@Qualifier!
@Retention(RUNTIME)!
@Target({FIELD, TYPE, METHOD, PARAMETER}) !
public @interface French {}!
!
@Qualifier!
@Retention(RUNTIME)!
@Target({FIELD, TYPE, METHOD, PARAMETER}) !
public @interface English {}
Qualifiers
@antoine_sd#CDIUni
@French!
public class FrenchHelloService implements HelloService {!
    public String hello() {!
        return "Bonjour tout le monde!";!
    }!
}!
!
@English!
public class EnglishHelloService implements HelloService {!
    public String hello() {!
        return "Hello World!";!
    }!
}
Qualifiers
@antoine_sd#CDIUni
public class MyBean {!
    @Inject @French HelloService service;!
    public void displayHello() {!
        display( service.hello();!
    }!
}!
public class MyBean {!
    @Inject @English HelloService service;!
    public void displayHello() {!
        display( service.hello();!
    }!
}
Qualifiers
@antoine_sd#CDIUni
@Qualifier!
@Retention(RUNTIME)!
@Target({FIELD, TYPE, METHOD, PARAMETER}) !
public @interface Language {!
!
    Languages value();!
!
@Nonbinding String description() default "";!
!
    public enum Languages { !
        FRENCH, ENGLISH!
    }!
}
Qualifiers with members
@antoine_sd#CDIUni
@Language(FRENCH)!
public class FrenchHelloService implements HelloService {!
    public String hello() {!
        return "Bonjour tout le monde!";!
    }!
}!
@Language(ENGLISH)!
public class EnglishHelloService implements HelloService {!
    public String hello() {!
        return "Hello World!";!
    }!
}
Qualifiers
@antoine_sd#CDIUni
public class MyBean {!
    @Inject @Language(ENGLISH) HelloService service;!
    public void displayHello() {!
        display( service.hello();!
    }!
}!
!
public class MyBean {!
    @Inject @Language(FRENCH) HelloService service;!
    public void displayHello() {!
        display( service.hello();!
    }!
}
Qualifiers
@antoine_sd#CDIUni
public class MyBean {!
    @Inject @French !
HelloService service;!
}!
!
@French @Console @Secured!
public class FrenchHelloService implements HelloService {!
!
}
Qualifiers
@antoine_sd#CDIUni
public class MyBean {!
    @Inject @French @Console!
HelloService service;!
}!
!
@French @Console @Secured!
public class FrenchHelloService implements HelloService {!
!
}
Qualifiers
@antoine_sd#CDIUni
public class MyBean {!
    @Inject @French @Console @Secured !
HelloService service;!
}!
!
@French @Console @Secured!
public class FrenchHelloService implements HelloService {!
!
}
Qualifiers
@antoine_sd#CDIUni
public class MyBean {!
    @Inject @French @Console @Secured !
HelloService service;!
}!
!
@French @Secured!
public class FrenchHelloService implements HelloService {!
!
}
Qualifiers
@antoine_sd#CDIUni
Reserved Qualifiers
@Default!
@Any!
@Named
@antoine_sd#CDIUni
public class MyBean {!
!
    @Inject Instance<HelloService> service;!
!
    public void displayHello() {!
        display( service.get().hello() );!
    }!
}
Programmatic lookup
@antoine_sd#CDIUni
public class MyBean {!
!
    @Inject Instance<HelloService> service;!
!
    public void displayHello() {!
        if (!service.isUnsatisfied()) {!
            display( service.get().hello() );!
        }!
    }!
}
Programmatic lookup
@antoine_sd#CDIUni
public class MyBean {!
!
    @Inject @Any Instance<HelloService> services;!
!
    public void displayHello() {!
        for (HelloService service : services) {!
            display( service.hello() );!
        }!
    }!
}
Programmatic lookup
@antoine_sd#CDIUni
public class MyBean {!
!
    @Inject @Any Instance<HelloService> services;!
!
    public void displayHello() {!
        display( !
            service.select(!
new AnnotationLiteral()<French> {})!
                .get() );!
    }!
}
Programmatic lookup
@antoine_sd#CDIUni
Contexts
•Manage bean lifecycle
•context helps container to choose when a bean should be generated and
destroyed
•it enforces the fact that a given bean is a singleton for a given context
•Built-in CDI contexts :
•@Dependent (default)
•@RequestScoped
•@SessionScoped
•@ConversationScoped
•@ApplicationScoped
•@Singleton
•You can create your own scope
@antoine_sd#CDIUni
@SessionScoped!
public class CartBean {!
!
    public void addItem(Item item) {!
...!
    } !
}
Contexts
@antoine_sd#CDIUni
@ApplicationScoped!
public class CartBean {!
!
    public void addItem(Item item) {!
...!
    } !
}
Contexts
FAIL
!!!
@antoine_sd#CDIUni
@ConversationScoped!
public class CartBean {!
!
    public void addItem(Item item) {!
...!
    } !
}
Contexts
@antoine_sd#CDIUni
@ThreadScoped!
public class CartBean {!
!
    public void addItem(Item item) {!
...!
    } !
}
Contexts
@antoine_sd#CDIUni
@HourScoped!
public class CartBean {!
!
    public void addItem(Item item) {!
...!
    } !
}
Contexts
@antoine_sd#CDIUni
@RandomScoped!
public class CartBean {!
!
    public void addItem(Item item) {!
...!
    } !
}
Contexts
@antoine_sd#CDIUni
@Produces!
public MyNonCDIClass myProducer() {!
return new MyNonCdiClass();!
}!
...!
@Inject!
MyNonCDIClass bean;!
Producers
@antoine_sd#CDIUni
@Produces!
@RequestScoped!
public FacesContext produceFacesContext() {!
return FacesContext.getCurrentInstance();!
}
Producers
@antoine_sd#CDIUni
@Produces!
public Logger produceLog(InjectionPoint injectionPoint) {!
return
Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());!
}
Producers
@antoine_sd#CDIUni
@Decorator!
@Priority(Interceptor.Priority.APPLICATION)!
public class HelloDecorator implements HelloService {!
!
    @Inject @Delegate HelloService service;!
!
    public String hello() {!
        return service.hello() + "-decorated";!
    }!
}
Decorators
@antoine_sd#CDIUni
@InterceptorBinding!
@Target({METHOD, TYPE}) !
@Retention(RUNTIME)!
public @interface Loggable {}
Interceptors
@antoine_sd#CDIUni
@Interceptor @Loggable !
public class LogInterceptor {!
  @AroundInvoke!
  public Object log(InvocationContext ic) throws Exception {!
   System.out.println("Entering " + ic.getMethod().getName());!
        try {!
            return ic.proceed(); !
        } finally {!
            System.out.println("Exiting " + ic.getMethod().getName());!
        }!
    } !
}
Interceptors
@antoine_sd#CDIUni
@Loggable!
public class MyBean {!
!
    @Inject HelloService service;!
!
    public void displayHello() {!
        display( service.hello();!
    }!
}
Interceptors
@antoine_sd#CDIUni
@Inject Event<Post> evt;!
!
…!
!
evt.fire(new Post("John Doe ", "Hello", ));!
!
…!
!
public void receiveEvt(@Observes Post evt) {!
    System.out.println("Received : " + evt.message());!
}
Events
@YourTwitterHandle#DVXFR14{session hashtag} @antoine_sd#CDIUni
CDI
extension
@antoine_sd#CDIUni
Extension for what use ?
•To change CDI container meta-data:
•AnnotatedType
•InjectionPoint / InjectionTarget
•BeanAttributes/Beans
•Producer
•Observer
!
•By observing the events triggered by CDI at boot time
@antoine_sd#CDIUni
How to build a CDI extension
•Create a class implementing
javax.enterprise.inject.spi.Extension
!
•Add some method that observes CDI lifecycle events to
modify Bean Manager meta data
!
•Add file :

META-INF/services/javax.enterprise.inject.spi.Extension

containing extension classname
@antoine_sd#CDIUni
public interface ProcessAnnotatedType<X> {

!
public AnnotatedType<X> getAnnotatedType();



public void setAnnotatedType(AnnotatedType<X> type);



public void veto();

}
!
public interface AnnotatedType<X> extends Annotated {



public Class<X> getJavaClass();



public Set<AnnotatedConstructor<X>> getConstructors();



public Set<AnnotatedMethod<? super X>> getMethods();



public Set<AnnotatedField<? super X>> getFields();

For Instance
•We can observe ProcessAnnotatedType event to change
a type information or force the container to ignore it.
@antoine_sd#CDIUni
public class VetoEntity implements Extension {

/**

* Version CDI 1.0

*/

public void vetoEntityLegacy(@Observes ProcessAnnotatedType<?> pat) {

AnnotatedType at = pat.getAnnotatedType();

if (at.isAnnotationPresent(Entity.class))

pat.veto(); 

}
/**

* Version CDI 1.1+

*/

public void vetoEntity(@Observes @WithAnnotations({Entity.class})ProcessAnnotatedType<?> pat) {

pat.veto(); 

}
}
Example 1 : Ignoring JPA entities
•A commonly admitted good practice is to avoid using
JPA entities as CDI beans.
•This extension excludes entities from the set of types
discovered by CDI.
@antoine_sd#CDIUni
Things to know
•Once application is bootstrapped, the Bean Manager is
in read only mode (no dynamic bean registration)
!
•Extensions are launched during bootstrap and are based
on CDI events
!
•You only have to @Observes built-in CDI event to create
your extensions
@antoine_sd#CDIUni
Example 2 : Add a Bean to CDI container
•There are many ways to add a bean to those
automatically discovered at boot time
!
•The easier method is to add an AnnotatedType to those
discovered by CDI.
@antoine_sd#CDIUni
public class HashMapAsBeanExtension implements Extension{



public void addHashMapAsAnnotatedType(@Observes BeforeBeanDiscovery bbd,
BeanManager beanManager)

{

bbd.addAnnotatedType(beanManager.createAnnotatedType(HashMap.class));

} 

}
Adding a HashMap Bean 1/2
•Observing BeforeBeanDiscovery event we can add a new
AnnotatedType based on HashMap classe.
@antoine_sd#CDIUni
@Decorator

@Priority(Interceptor.Priority.APPLICATION)

public abstract class MapDecorator implements Map{



@Inject

@Delegate

Map delegate;



@Override

public Object put(Object key, Object value) {

System.out.println("------- Putting Something in the Map -----------");

if ("key".equals(key)) {

System.out.println("==== Not adding key key ======");

return null;

} 

return delegate.put(key,value);

}

}
Adding a HashMap Bean 2/2
•Once created we can add CDI service on this HashMap
bean. See that Decorator.
@antoine_sd#CDIUni
CDI 1.1 Lifecycle
Before Bean
Discovery
Process Bean
Process
Annotated
Type
Scan	

Archive
Application	

Running
After
Deployment
Validation
Before
Shutdown
Undeploy
Application
Process
Producer
After Bean
Discovery
Process	

Injection
Target
Process
Observer
Method
Process	

Injection
Point
Process Bean
Attributes
After Type
Discovery
événement unique
événements multiples
étape interne
Deployment
starts
Bean
eligibility
check
@antoine_sd#CDIUni
Scheduler Extension1/4
•This extension example comes from Apache Deltaspike
project. It’s a simplified version.
!
•We want to be able to schedule jobs from by using
annotation @Schedule.
@antoine_sd#CDIUni
public class SchedulerExtension implements Extension {

private List<Class> foundManagedJobClasses = new ArrayList<Class>();

private Scheduler scheduler;



public <X> void findScheduledJobs(@Observes @WithAnnotations({ Scheduled.class }) ProcessAnnotatedType<X> pat) {

Class<X> beanClass = pat.getAnnotatedType().getJavaClass();

this.foundManagedJobClasses.add(beanClass);

}



public <X> void scheduleJobs(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {

initScheduler(afterBeanDiscovery)

List<String> foundJobNames = new ArrayList<String>();

for (Class jobClass : this.foundManagedJobClasses) {

foundJobNames.add(jobClass.getSimpleName());

this.scheduler.registerNewJob(jobClass);

}

}



public <X> void stopScheduler(@Observes BeforeShutdown beforeShutdown) {

if (this.scheduler != null) {

this.scheduler.stop();

this.scheduler = null;

}

}
private void initScheduler(AfterBeanDiscovery afterBeanDiscovery) {

this.scheduler = new QuartzScheduler();

this.scheduler.start();

}
}
Scheduler extension 2/4 (extension code)
@antoine_sd#CDIUni
Steps used in the extension
Before Bean
Discovery
Process Bean
Process
Annotated
Type
Scan	

Archive
Application	

Running
After
Deployment
Validation
Before
Shutdown
Undeploy
Application
Process
Producer
After Bean
Discovery
Process	

Injection
Target
Process
Observer
Method
Process	

Injection
Point
Process Bean
Attributes
After Type
Discovery
occurs once
occurs on each elt
Internal step w/o hook
Deployment
starts
Bean
eligibility
check
@antoine_sd#CDIUni
public interface Scheduler<T>

{

void start();



void stop();



void pauseJob(Class<? extends T> jobClass);



void resumeJob(Class<? extends T> jobClass);



void interruptJob(Class<? extends T> jobClass);



boolean isExecutingJob(Class<? extends T> jobClass);



void registerNewJob(Class<? extends T> jobClass);



void startJobManually(Class<? extends T> jobClass);



<S> S unwrap(Class<? extends S> schedulerClass);

}
Scheduler Extension 3/4 (scheduler interface)
@antoine_sd#CDIUni
@ApplicationScoped

public class SchedulerProducer

{

@Inject

private SchedulerExtension schedulerExtension;



@Produces

@ApplicationScoped

protected Scheduler produceScheduler()

{

return this.schedulerExtension.getScheduler();

}

}
Scheduler extension 4/4 (scheduler producer)

More Related Content

What's hot

Supporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan HerrmannSupporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
Eclipse Day India
 
Clean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code CampClean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code Camp
Theo Jungeblut
 

What's hot (19)

Supporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan HerrmannSupporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
Supporting Java™ 9 in Eclipse - A critical perspective - Stephan Herrmann
 
Reverse engineering and instrumentation of android apps
Reverse engineering and instrumentation of android appsReverse engineering and instrumentation of android apps
Reverse engineering and instrumentation of android apps
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
ProbeDroid - Crafting Your Own Dynamic Instrument Tool on Android for App Beh...
ProbeDroid - Crafting Your Own Dynamic Instrument Tool on Android for App Beh...ProbeDroid - Crafting Your Own Dynamic Instrument Tool on Android for App Beh...
ProbeDroid - Crafting Your Own Dynamic Instrument Tool on Android for App Beh...
 
[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android
 
DevSecOps for Developers, How To Start (ETC 2020)
DevSecOps for Developers, How To Start (ETC 2020)DevSecOps for Developers, How To Start (ETC 2020)
DevSecOps for Developers, How To Start (ETC 2020)
 
Android Native Development Kit
Android Native Development KitAndroid Native Development Kit
Android Native Development Kit
 
Scala on androids
Scala on androidsScala on androids
Scala on androids
 
Refactoring a go project
Refactoring a go projectRefactoring a go project
Refactoring a go project
 
Android NDK: Entrando no Mundo Nativo
Android NDK: Entrando no Mundo NativoAndroid NDK: Entrando no Mundo Nativo
Android NDK: Entrando no Mundo Nativo
 
Android ndk: Entering the native world
Android ndk: Entering the native worldAndroid ndk: Entering the native world
Android ndk: Entering the native world
 
Steelcon 2015 Reverse-Engineering Obfuscated Android Applications
Steelcon 2015 Reverse-Engineering Obfuscated Android ApplicationsSteelcon 2015 Reverse-Engineering Obfuscated Android Applications
Steelcon 2015 Reverse-Engineering Obfuscated Android Applications
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013
 
Clean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code CampClean Code Part III - Craftsmanship at SoCal Code Camp
Clean Code Part III - Craftsmanship at SoCal Code Camp
 
How to reverse engineer Android applications
How to reverse engineer Android applicationsHow to reverse engineer Android applications
How to reverse engineer Android applications
 
JavaOne 2015 CON7547 "Beyond the Coffee Cup: Leveraging Java Runtime Technolo...
JavaOne 2015 CON7547 "Beyond the Coffee Cup: Leveraging Java Runtime Technolo...JavaOne 2015 CON7547 "Beyond the Coffee Cup: Leveraging Java Runtime Technolo...
JavaOne 2015 CON7547 "Beyond the Coffee Cup: Leveraging Java Runtime Technolo...
 
Android develop guideline
Android develop guidelineAndroid develop guideline
Android develop guideline
 
.NET Profilers and IL Rewriting - DDD Melbourne 2
.NET Profilers and IL Rewriting - DDD Melbourne 2.NET Profilers and IL Rewriting - DDD Melbourne 2
.NET Profilers and IL Rewriting - DDD Melbourne 2
 

Viewers also liked

Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5
Arun Gupta
 

Viewers also liked (20)

Mute Java EE DNA with CDI
Mute Java EE DNA with CDI Mute Java EE DNA with CDI
Mute Java EE DNA with CDI
 
Adopt a JSR: CDI 2.0 at Devoxx UK
Adopt a JSR: CDI 2.0 at Devoxx UKAdopt a JSR: CDI 2.0 at Devoxx UK
Adopt a JSR: CDI 2.0 at Devoxx UK
 
Java EE, un ami qui vous veut du bien
Java EE, un ami qui vous veut du bienJava EE, un ami qui vous veut du bien
Java EE, un ami qui vous veut du bien
 
Devoxx Java Social and Agorava
Devoxx Java Social and AgoravaDevoxx Java Social and Agorava
Devoxx Java Social and Agorava
 
Invoke dynamite in Java EE with invoke dynamic
Invoke dynamite in Java EE with invoke dynamicInvoke dynamite in Java EE with invoke dynamic
Invoke dynamite in Java EE with invoke dynamic
 
The path to cdi 2.0
The path to cdi 2.0The path to cdi 2.0
The path to cdi 2.0
 
Going further with CDI 1.2
Going further with CDI 1.2Going further with CDI 1.2
Going further with CDI 1.2
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
CDI mis en pratique avec Seam Social et Weld OSGI
CDI mis en pratique avec Seam Social et Weld OSGICDI mis en pratique avec Seam Social et Weld OSGI
CDI mis en pratique avec Seam Social et Weld OSGI
 
Java EE 6 & Spring: A Lover's Quarrel
Java EE 6 & Spring: A Lover's QuarrelJava EE 6 & Spring: A Lover's Quarrel
Java EE 6 & Spring: A Lover's Quarrel
 
The Magnificent java EE 7 in Wildfly-O-Rama
The Magnificent java EE 7 in Wildfly-O-RamaThe Magnificent java EE 7 in Wildfly-O-Rama
The Magnificent java EE 7 in Wildfly-O-Rama
 
1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand1/3 : introduction to CDI - Antoine Sabot-Durand
1/3 : introduction to CDI - Antoine Sabot-Durand
 
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.Pilgrim
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.PilgrimJavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.Pilgrim
JavaEE & GlassFish UG - Digital JavaEE 7 New & Noteworthy by P.Pilgrim
 
AAI-1713 Introduction to Java EE 7
AAI-1713 Introduction to Java EE 7AAI-1713 Introduction to Java EE 7
AAI-1713 Introduction to Java EE 7
 
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final2012 04-09-v2-tdp-1167-cdi-bestpractices-final
2012 04-09-v2-tdp-1167-cdi-bestpractices-final
 
Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5Java EE 7: Boosting Productivity and Embracing HTML5
Java EE 7: Boosting Productivity and Embracing HTML5
 
50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes50 New Features of Java EE 7 in 50 minutes
50 New Features of Java EE 7 in 50 minutes
 
Fais ce que tu veux avec Java EE - Devoxx France 2014
Fais ce que tu veux avec Java EE - Devoxx France 2014Fais ce que tu veux avec Java EE - Devoxx France 2014
Fais ce que tu veux avec Java EE - Devoxx France 2014
 
50 features of Java EE 7 in 50 minutes at JavaZone 2014
50 features of Java EE 7 in 50 minutes at JavaZone 201450 features of Java EE 7 in 50 minutes at JavaZone 2014
50 features of Java EE 7 in 50 minutes at JavaZone 2014
 
Deploying Web Applications with WildFly 8
Deploying Web Applications with WildFly 8Deploying Web Applications with WildFly 8
Deploying Web Applications with WildFly 8
 

Similar to CDI 1.1 university

Android Scripting
Android ScriptingAndroid Scripting
Android Scripting
Juan Gomez
 

Similar to CDI 1.1 university (20)

Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
Green Light for the Apps with Calaba.sh - DroidCon Paris 2014
Green Light for the Apps with Calaba.sh - DroidCon Paris 2014Green Light for the Apps with Calaba.sh - DroidCon Paris 2014
Green Light for the Apps with Calaba.sh - DroidCon Paris 2014
 
Codeception Testing Framework -- English #phpkansai
Codeception Testing Framework -- English #phpkansaiCodeception Testing Framework -- English #phpkansai
Codeception Testing Framework -- English #phpkansai
 
Angular 2 and NativeScript
Angular 2 and NativeScriptAngular 2 and NativeScript
Angular 2 and NativeScript
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
Ignite your app development with Angular, NativeScript and Firebase
Ignite your app development with Angular, NativeScript and FirebaseIgnite your app development with Angular, NativeScript and Firebase
Ignite your app development with Angular, NativeScript and Firebase
 
Matteo Vaccari - TDD per Android | Codemotion Milan 2015
Matteo Vaccari - TDD per Android | Codemotion Milan 2015Matteo Vaccari - TDD per Android | Codemotion Milan 2015
Matteo Vaccari - TDD per Android | Codemotion Milan 2015
 
Kotlin for android 2019
Kotlin for android 2019Kotlin for android 2019
Kotlin for android 2019
 
Develop Maintainable Apps - edUiConf
Develop Maintainable Apps - edUiConfDevelop Maintainable Apps - edUiConf
Develop Maintainable Apps - edUiConf
 
API Documentation Workshop tcworld India 2015
API Documentation Workshop tcworld India 2015API Documentation Workshop tcworld India 2015
API Documentation Workshop tcworld India 2015
 
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJSDeveloping Modern Java Web Applications with Java EE 7 and AngularJS
Developing Modern Java Web Applications with Java EE 7 and AngularJS
 
Titanium Alloy Tutorial
Titanium Alloy TutorialTitanium Alloy Tutorial
Titanium Alloy Tutorial
 
Beyond MVC: from Model to Domain
Beyond MVC: from Model to DomainBeyond MVC: from Model to Domain
Beyond MVC: from Model to Domain
 
Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013
 
Swift meetup22june2015
Swift meetup22june2015Swift meetup22june2015
Swift meetup22june2015
 
Android Scripting
Android ScriptingAndroid Scripting
Android Scripting
 
Getting started with Appcelerator Titanium
Getting started with Appcelerator TitaniumGetting started with Appcelerator Titanium
Getting started with Appcelerator Titanium
 
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
Beyond Fluffy Bunny. How I leveraged WebObjects in my lean startup.
 
Scott Mason: Enhancing the User Interface Using Titanium Modules
Scott Mason: Enhancing the User Interface Using Titanium ModulesScott Mason: Enhancing the User Interface Using Titanium Modules
Scott Mason: Enhancing the User Interface Using Titanium Modules
 
How to build Sdk? Best practices
How to build Sdk? Best practicesHow to build Sdk? Best practices
How to build Sdk? Best practices
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 

Recently uploaded (20)

TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Modernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using BallerinaModernizing Legacy Systems Using Ballerina
Modernizing Legacy Systems Using Ballerina
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Navigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern EnterpriseNavigating Identity and Access Management in the Modern Enterprise
Navigating Identity and Access Management in the Modern Enterprise
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 

CDI 1.1 university

  • 1. @antoine_sd#CDIUni CDI University @antoine_sd Red Hat, http://cdi-spec.org CDI specification leader
  • 2. @antoine_sd#CDIUni Antoine Sabot-Durand •Senior Software Developer @Red Hat ! •Java & OSS : •CDI co-spec lead •CDI eco-system development •Tech Lead on Agorava ! •@antoine_sd •@cdispec
  • 4. @antoine_sd#CDIUni •CDI is a lot of things •Java EE IoC standard also working on Java SE •Context management •Observer pattern included •The « cement » between most Java EE spec •An evolution engine for Java EE thanks to portable extensions •All of this based on java strong typing Context & Dependency Injection
  • 5. @antoine_sd#CDIUni CDI history & actual state •Main milestone : •December 2009 : CDI 1.0 •June 2013 : CDI 1.1 •April 2014 : CDI 1.2 •Summer 2014 : CDI 2.0 development starting •Implementations : •JBoss Weld (RI) : WildFly, JBoss EAP, Glassfish, Weblogic •Apache OpenWebBeans : TomEE, Websphere •Check http://cdi-spec.org
  • 6. @antoine_sd#CDIUni CDI activated by default in Java EE 7 •In Java EE 6, you must add a beans.xml file to your archive •No need to in Java EE 7 but you can still to have an explicit activation (behave differently) beans.xml
  • 7. @antoine_sd#CDIUni Bean •In Java EE 6 everything is a Managed Bean •Managed beans are basic components •They are managed by the container •They all have a lifecycle •They can be intercepted (AOP) •They can be injected •Accessible from outside CDI code.
  • 9. @antoine_sd#CDIUni public class HelloService {!     public String hello() {!         return "Hello World!";!     }! } Dependency Injection
  • 10. @antoine_sd#CDIUni public class MyBean {! !     private HelloService service;! !     @Inject!     public MyBean(HelloService service) {!         this.service = service;!     }!     public void displayHello() {!         display( service.hello();!     }! } Dependency Injection in constructor
  • 11. @antoine_sd#CDIUni public class MyBean {! !     private HelloService service;! !     @Inject!     public void setService(HelloService service) {!         this.service = service;!     }!     public void displayHello() {!         display( service.hello();!     }! } Dependency Injection in setter
  • 12. @antoine_sd#CDIUni public class MyBean {! !     @Inject HelloService service;! !     public void displayHello() {!         display( service.hello();!     }! } Dependency Injection in field
  • 13. @antoine_sd#CDIUni public interface HelloService {!     public String hello();! }! public class FrenchHelloService implements HelloService {!     public String hello() {!         return "Bonjour tout le monde!";!     }! }! public class EnglishHelloService implements HelloService {!     public String hello() {!         return "Hello World!";!     }! } Qualifiers
  • 14. @antoine_sd#CDIUni @Qualifier! @Retention(RUNTIME)! @Target({FIELD, TYPE, METHOD, PARAMETER}) ! public @interface French {}! ! @Qualifier! @Retention(RUNTIME)! @Target({FIELD, TYPE, METHOD, PARAMETER}) ! public @interface English {} Qualifiers
  • 15. @antoine_sd#CDIUni @French! public class FrenchHelloService implements HelloService {!     public String hello() {!         return "Bonjour tout le monde!";!     }! }! ! @English! public class EnglishHelloService implements HelloService {!     public String hello() {!         return "Hello World!";!     }! } Qualifiers
  • 16. @antoine_sd#CDIUni public class MyBean {!     @Inject @French HelloService service;!     public void displayHello() {!         display( service.hello();!     }! }! public class MyBean {!     @Inject @English HelloService service;!     public void displayHello() {!         display( service.hello();!     }! } Qualifiers
  • 17. @antoine_sd#CDIUni @Qualifier! @Retention(RUNTIME)! @Target({FIELD, TYPE, METHOD, PARAMETER}) ! public @interface Language {! !     Languages value();! ! @Nonbinding String description() default "";! !     public enum Languages { !         FRENCH, ENGLISH!     }! } Qualifiers with members
  • 18. @antoine_sd#CDIUni @Language(FRENCH)! public class FrenchHelloService implements HelloService {!     public String hello() {!         return "Bonjour tout le monde!";!     }! }! @Language(ENGLISH)! public class EnglishHelloService implements HelloService {!     public String hello() {!         return "Hello World!";!     }! } Qualifiers
  • 19. @antoine_sd#CDIUni public class MyBean {!     @Inject @Language(ENGLISH) HelloService service;!     public void displayHello() {!         display( service.hello();!     }! }! ! public class MyBean {!     @Inject @Language(FRENCH) HelloService service;!     public void displayHello() {!         display( service.hello();!     }! } Qualifiers
  • 20. @antoine_sd#CDIUni public class MyBean {!     @Inject @French ! HelloService service;! }! ! @French @Console @Secured! public class FrenchHelloService implements HelloService {! ! } Qualifiers
  • 21. @antoine_sd#CDIUni public class MyBean {!     @Inject @French @Console! HelloService service;! }! ! @French @Console @Secured! public class FrenchHelloService implements HelloService {! ! } Qualifiers
  • 22. @antoine_sd#CDIUni public class MyBean {!     @Inject @French @Console @Secured ! HelloService service;! }! ! @French @Console @Secured! public class FrenchHelloService implements HelloService {! ! } Qualifiers
  • 23. @antoine_sd#CDIUni public class MyBean {!     @Inject @French @Console @Secured ! HelloService service;! }! ! @French @Secured! public class FrenchHelloService implements HelloService {! ! } Qualifiers
  • 25. @antoine_sd#CDIUni public class MyBean {! !     @Inject Instance<HelloService> service;! !     public void displayHello() {!         display( service.get().hello() );!     }! } Programmatic lookup
  • 26. @antoine_sd#CDIUni public class MyBean {! !     @Inject Instance<HelloService> service;! !     public void displayHello() {!         if (!service.isUnsatisfied()) {!             display( service.get().hello() );!         }!     }! } Programmatic lookup
  • 27. @antoine_sd#CDIUni public class MyBean {! !     @Inject @Any Instance<HelloService> services;! !     public void displayHello() {!         for (HelloService service : services) {!             display( service.hello() );!         }!     }! } Programmatic lookup
  • 28. @antoine_sd#CDIUni public class MyBean {! !     @Inject @Any Instance<HelloService> services;! !     public void displayHello() {!         display( !             service.select(! new AnnotationLiteral()<French> {})!                 .get() );!     }! } Programmatic lookup
  • 29. @antoine_sd#CDIUni Contexts •Manage bean lifecycle •context helps container to choose when a bean should be generated and destroyed •it enforces the fact that a given bean is a singleton for a given context •Built-in CDI contexts : •@Dependent (default) •@RequestScoped •@SessionScoped •@ConversationScoped •@ApplicationScoped •@Singleton •You can create your own scope
  • 30. @antoine_sd#CDIUni @SessionScoped! public class CartBean {! !     public void addItem(Item item) {! ...!     } ! } Contexts
  • 31. @antoine_sd#CDIUni @ApplicationScoped! public class CartBean {! !     public void addItem(Item item) {! ...!     } ! } Contexts FAIL !!!
  • 32. @antoine_sd#CDIUni @ConversationScoped! public class CartBean {! !     public void addItem(Item item) {! ...!     } ! } Contexts
  • 33. @antoine_sd#CDIUni @ThreadScoped! public class CartBean {! !     public void addItem(Item item) {! ...!     } ! } Contexts
  • 34. @antoine_sd#CDIUni @HourScoped! public class CartBean {! !     public void addItem(Item item) {! ...!     } ! } Contexts
  • 35. @antoine_sd#CDIUni @RandomScoped! public class CartBean {! !     public void addItem(Item item) {! ...!     } ! } Contexts
  • 36. @antoine_sd#CDIUni @Produces! public MyNonCDIClass myProducer() {! return new MyNonCdiClass();! }! ...! @Inject! MyNonCDIClass bean;! Producers
  • 37. @antoine_sd#CDIUni @Produces! @RequestScoped! public FacesContext produceFacesContext() {! return FacesContext.getCurrentInstance();! } Producers
  • 38. @antoine_sd#CDIUni @Produces! public Logger produceLog(InjectionPoint injectionPoint) {! return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());! } Producers
  • 39. @antoine_sd#CDIUni @Decorator! @Priority(Interceptor.Priority.APPLICATION)! public class HelloDecorator implements HelloService {! !     @Inject @Delegate HelloService service;! !     public String hello() {!         return service.hello() + "-decorated";!     }! } Decorators
  • 41. @antoine_sd#CDIUni @Interceptor @Loggable ! public class LogInterceptor {!   @AroundInvoke!   public Object log(InvocationContext ic) throws Exception {!    System.out.println("Entering " + ic.getMethod().getName());!         try {!             return ic.proceed(); !         } finally {!             System.out.println("Exiting " + ic.getMethod().getName());!         }!     } ! } Interceptors
  • 42. @antoine_sd#CDIUni @Loggable! public class MyBean {! !     @Inject HelloService service;! !     public void displayHello() {!         display( service.hello();!     }! } Interceptors
  • 43. @antoine_sd#CDIUni @Inject Event<Post> evt;! ! …! ! evt.fire(new Post("John Doe ", "Hello", ));! ! …! ! public void receiveEvt(@Observes Post evt) {!     System.out.println("Received : " + evt.message());! } Events
  • 45. @antoine_sd#CDIUni Extension for what use ? •To change CDI container meta-data: •AnnotatedType •InjectionPoint / InjectionTarget •BeanAttributes/Beans •Producer •Observer ! •By observing the events triggered by CDI at boot time
  • 46. @antoine_sd#CDIUni How to build a CDI extension •Create a class implementing javax.enterprise.inject.spi.Extension ! •Add some method that observes CDI lifecycle events to modify Bean Manager meta data ! •Add file :
 META-INF/services/javax.enterprise.inject.spi.Extension
 containing extension classname
  • 47. @antoine_sd#CDIUni public interface ProcessAnnotatedType<X> {
 ! public AnnotatedType<X> getAnnotatedType();
 
 public void setAnnotatedType(AnnotatedType<X> type);
 
 public void veto();
 } ! public interface AnnotatedType<X> extends Annotated {
 
 public Class<X> getJavaClass();
 
 public Set<AnnotatedConstructor<X>> getConstructors();
 
 public Set<AnnotatedMethod<? super X>> getMethods();
 
 public Set<AnnotatedField<? super X>> getFields();
 For Instance •We can observe ProcessAnnotatedType event to change a type information or force the container to ignore it.
  • 48. @antoine_sd#CDIUni public class VetoEntity implements Extension {
 /**
 * Version CDI 1.0
 */
 public void vetoEntityLegacy(@Observes ProcessAnnotatedType<?> pat) {
 AnnotatedType at = pat.getAnnotatedType();
 if (at.isAnnotationPresent(Entity.class))
 pat.veto(); 
 } /**
 * Version CDI 1.1+
 */
 public void vetoEntity(@Observes @WithAnnotations({Entity.class})ProcessAnnotatedType<?> pat) {
 pat.veto(); 
 } } Example 1 : Ignoring JPA entities •A commonly admitted good practice is to avoid using JPA entities as CDI beans. •This extension excludes entities from the set of types discovered by CDI.
  • 49. @antoine_sd#CDIUni Things to know •Once application is bootstrapped, the Bean Manager is in read only mode (no dynamic bean registration) ! •Extensions are launched during bootstrap and are based on CDI events ! •You only have to @Observes built-in CDI event to create your extensions
  • 50. @antoine_sd#CDIUni Example 2 : Add a Bean to CDI container •There are many ways to add a bean to those automatically discovered at boot time ! •The easier method is to add an AnnotatedType to those discovered by CDI.
  • 51. @antoine_sd#CDIUni public class HashMapAsBeanExtension implements Extension{
 
 public void addHashMapAsAnnotatedType(@Observes BeforeBeanDiscovery bbd, BeanManager beanManager)
 {
 bbd.addAnnotatedType(beanManager.createAnnotatedType(HashMap.class));
 } 
 } Adding a HashMap Bean 1/2 •Observing BeforeBeanDiscovery event we can add a new AnnotatedType based on HashMap classe.
  • 52. @antoine_sd#CDIUni @Decorator
 @Priority(Interceptor.Priority.APPLICATION)
 public abstract class MapDecorator implements Map{
 
 @Inject
 @Delegate
 Map delegate;
 
 @Override
 public Object put(Object key, Object value) {
 System.out.println("------- Putting Something in the Map -----------");
 if ("key".equals(key)) {
 System.out.println("==== Not adding key key ======");
 return null;
 } 
 return delegate.put(key,value);
 }
 } Adding a HashMap Bean 2/2 •Once created we can add CDI service on this HashMap bean. See that Decorator.
  • 53. @antoine_sd#CDIUni CDI 1.1 Lifecycle Before Bean Discovery Process Bean Process Annotated Type Scan Archive Application Running After Deployment Validation Before Shutdown Undeploy Application Process Producer After Bean Discovery Process Injection Target Process Observer Method Process Injection Point Process Bean Attributes After Type Discovery événement unique événements multiples étape interne Deployment starts Bean eligibility check
  • 54. @antoine_sd#CDIUni Scheduler Extension1/4 •This extension example comes from Apache Deltaspike project. It’s a simplified version. ! •We want to be able to schedule jobs from by using annotation @Schedule.
  • 55. @antoine_sd#CDIUni public class SchedulerExtension implements Extension {
 private List<Class> foundManagedJobClasses = new ArrayList<Class>();
 private Scheduler scheduler;
 
 public <X> void findScheduledJobs(@Observes @WithAnnotations({ Scheduled.class }) ProcessAnnotatedType<X> pat) {
 Class<X> beanClass = pat.getAnnotatedType().getJavaClass();
 this.foundManagedJobClasses.add(beanClass);
 }
 
 public <X> void scheduleJobs(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
 initScheduler(afterBeanDiscovery)
 List<String> foundJobNames = new ArrayList<String>();
 for (Class jobClass : this.foundManagedJobClasses) {
 foundJobNames.add(jobClass.getSimpleName());
 this.scheduler.registerNewJob(jobClass);
 }
 }
 
 public <X> void stopScheduler(@Observes BeforeShutdown beforeShutdown) {
 if (this.scheduler != null) {
 this.scheduler.stop();
 this.scheduler = null;
 }
 } private void initScheduler(AfterBeanDiscovery afterBeanDiscovery) {
 this.scheduler = new QuartzScheduler();
 this.scheduler.start();
 } } Scheduler extension 2/4 (extension code)
  • 56. @antoine_sd#CDIUni Steps used in the extension Before Bean Discovery Process Bean Process Annotated Type Scan Archive Application Running After Deployment Validation Before Shutdown Undeploy Application Process Producer After Bean Discovery Process Injection Target Process Observer Method Process Injection Point Process Bean Attributes After Type Discovery occurs once occurs on each elt Internal step w/o hook Deployment starts Bean eligibility check
  • 57. @antoine_sd#CDIUni public interface Scheduler<T>
 {
 void start();
 
 void stop();
 
 void pauseJob(Class<? extends T> jobClass);
 
 void resumeJob(Class<? extends T> jobClass);
 
 void interruptJob(Class<? extends T> jobClass);
 
 boolean isExecutingJob(Class<? extends T> jobClass);
 
 void registerNewJob(Class<? extends T> jobClass);
 
 void startJobManually(Class<? extends T> jobClass);
 
 <S> S unwrap(Class<? extends S> schedulerClass);
 } Scheduler Extension 3/4 (scheduler interface)
  • 58. @antoine_sd#CDIUni @ApplicationScoped
 public class SchedulerProducer
 {
 @Inject
 private SchedulerExtension schedulerExtension;
 
 @Produces
 @ApplicationScoped
 protected Scheduler produceScheduler()
 {
 return this.schedulerExtension.getScheduler();
 }
 } Scheduler extension 4/4 (scheduler producer)