SlideShare une entreprise Scribd logo
1  sur  63
Télécharger pour lire hors ligne
INTRODUCTIONTO CONTEXTS AND
DEPENDENCY INJECTION (CDI)
@antoine_sd
ANTOINE SABOT-DURAND
• Senior Software Engineer @Red Hat
• Java & OSS :
• CDI co-spec lead
• CDI community development
• Tech Lead on Agorava
• @antoine_sd
WHAT IS CDI ?
• Java EE dependency injection standard
• Strong typed and type safe
• Context management
• Observer pattern included (Event bus)
• Highly extensible
A BIT OF HISTORY
Dec 2009 June 2013 Apr 2014 Sep 2014
CDI
1.0
(Java
EE
6)
CDI
1.1
(Java
EE
7)
CDI
1.2
(1.1
MR)
CDI
2.0
Starts
Q1 2016
CDI
2.0
released
IMPLEMENTATIONS
JBoss Weld (Reference Implementation) Apache Open WebBeans
CDI ACTIVATION
• In CDI 1.0, you must add a beans.xml file to your archive
• Since CDI 1.1, it’s activated by default:
• All classes having a “bean defining annotation” become a bean
• You can still use beans.xml file to activate CDI explicitly or
deactivate it
THE CDI BEAN
• In Java EE 6 and 7 everything is a Bean including (EJB session beans)
• 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.
BASIC DEPENDENCY INJECTION
@Inject
THIS IS A BEAN
public class HelloService {
    public String hello() {
        return "Hello World!";
    }
}
DI IN CONSTRUCTOR
public class MyBean {
    private HelloService service;
    @Inject
    public MyBean(HelloService service) {
        this.service = service;
    }
}
DI IN INITIALISER METHOD
public class MyBean {
    private HelloService service;
    @Inject
    public void initService(HelloService service) {
        this.service = service;
    }
}
DI IN FIELD
public class MyBean {
    
@Inject
private HelloService service;
    public void displayHello() {
        display(service.hello();
    }
}
NOTYPE ERASURE IN CDI
public class MyBean {
    @Inject Service<User> userService;
@Inject Service<Staff> staffService;
    
}
NOTYPE ERASURE IN CDI
public class MyBean {
    @Inject Service<User> userService;
@Inject Service<Staff> staffService;
    
}
This works
TYPES OF A BEAN
• A bean will be a candidate for all “injection point” whose type
belongs to its types set
• Bean types set contains its type, all its implementing interfaces and all
its ancestors including Object.
• Bean types can be restricted by using @Typed annotation (Object is
always in the set)
TYPES OF A BEAN
public class HelloService {

//Types set : HelloService, Object

}



public class FrenchHelloService extends GenericService implements HelloService {

//Types set : FrenchHelloService, GenericService, HelloService, Object 

}



@Typed({HelloService.class,GenericService.class})

public class FrenchHelloService extends GenericService implements HelloService {

//Types set : GenericService, HelloService, Object 

}
USING QUALIFIERSTO DISTINGUISH
BEANS OFTHE SAMETYPE
TWO SERVICE IMPLEMENTATIONS…
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!";
    }
}
…NEED QUALIFIERS…
@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD, PARAMETER})
public @interface French {}
@Qualifier
@Retention(RUNTIME)
@Target({FIELD, TYPE, METHOD, PARAMETER})
public @interface English {}
…TO BE DISTINGUISHED.
@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!";
    }
}
QUALIFIED INJECTION POINTS
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 CAN HAVE MEMBERS
@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 1/2
@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 WITH MEMBERS 2/2
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();
    }
}
MULTIPLE QUALIFIERS
public class MyBean {
    @Inject @French
HelloService service;
}
@French @Console @Secured
public class FrenchHelloService implements HelloService {
}
MULTIPLE QUALIFIERS
public class MyBean {
    @Inject @French @Console
HelloService service;
}
@French @Console @Secured
public class FrenchHelloService implements HelloService {
}
MULTIPLE QUALIFIERS
public class MyBean {
    @Inject @French @Console @Secured
HelloService service;
}
@French @Console @Secured
public class FrenchHelloService implements HelloService {
}
MULTIPLE QUALIFIERS
public class MyBean {
    @Inject @French @Console @Secured
HelloService service;
}
@French @Secured
public class FrenchHelloService implements HelloService {
}
MULTIPLE QUALIFIERS
public class MyBean {
    @Inject @French @Console @Secured
HelloService service;
}
@French @Secured
public class FrenchHelloService implements HelloService {
}
RESERVED QUALIFIERS
@Default
@Any
@Named
PROGRAMMATIC LOOKUP
SOMETIMES CALLED “LAZY INJECTION”
public class MyBean {
    @Inject Instance<HelloService> service;
    public void displayHello() {
        display( service.get().hello() );
    }
}
CHECK BEAN EXISTENCE AT RUNTIME
public class MyBean {
    @Inject Instance<HelloService> service;
    public void displayHello() {
        if (!service.isUnsatisfied()) {
            display( service.get().hello() );
        }
    }
}
LOOP ON ALL BEANS OF A GIVENTYPE
public class MyBean {
    @Inject @Any Instance<HelloService> services;
    public void displayHello() {
        for (HelloService service : services) {
            display( service.hello() );
        }
    }
}
SELECT A QUALIFIER AT RUNTIME
public class MyBean {
    @Inject @Any Instance<HelloService> services;
    public void displayHello() {
        display(
            service.select(
new AnnotationLiteral()<French> {})
                .get() );
    }
}
CONTEXTS
CONTEXTS MANAGE BEANS LIFECYCLE
• They helps container to choose when a bean should be instantiated and destroyed
• They enforce the fact that a given bean is a singleton for a given context
• Built-in CDI contexts :
• @Dependent (default)
• @ApplicationScoped, @SessionScoped, @RequestScoped
• @ConversationScoped
• @Singleton
• You can create your own scope
CHOOSINGTHE RIGHT CONTEXT
@SessionScoped
public class CartBean {
    public void addItem(Item item) {
...
    }
}
CHOOSINGTHE RIGHT CONTEXT
@ApplicationScoped
public class CartBean {
    public void addItem(Item item) {
...
    }
}
CHOOSINGTHE RIGHT CONTEXT
@ApplicationScoped
public class CartBean {
    public void addItem(Item item) {
...
    }
}
FAIL
!!!
CONVERSATION IS MANAGE BY DEV
@ConversationScoped
public class CartBean {
    public void addItem(Item item) {
...
    }
}
NEW CONTEXTS CAN BE CREATED
@ThreadScoped
public class CartBean {
    public void addItem(Item item) {
...
    }
}
PRODUCERS
CREATING BEAN FROM ANY CLASS
@Produces
public MyNonCDIClass myProducer() {
return new MyNonCdiClass();
}
...
@Inject
MyNonCDIClass bean;
DISPOSER ARE OPTIONAL
@Produces
public MyNonCDIClass myProducer() {
return new MyNonCdiClass();
}
// Will be call at the instance end of life
public void releaseMyInstance(@Disposes MyNonCdiClass inst) {
inst.clean();
}
PRODUCERS MAY HAVE A SCOPE
@Produces
@RequestScoped
public FacesContext produceFacesContext() {
return FacesContext.getCurrentInstance();
}
GETTING INFO FROM INJECTION POINT
@Produces
public Logger produceLog(InjectionPoint injectionPoint) {
return Logger.getLogger(injectionPoint.getMember()
.getDeclaringClass().getName());
}
REMEMBER :“NOTYPE ERASURE”
@Produces

public <K, V> Map<K, V> produceMap(InjectionPoint ip) {

if (valueIsNumber(ip.getType())) {

return new TreeMap<K, V>();

}

return new HashMap<K, V>();

}
EVENTS
A NICE WAYTO ADD DECOUPLING
public class FirstBean {
@Inject Event<Post> postEvent;
public void saveNewPost(Post myPost) {
postEvent.fire(myPost);
}
}
public class SecondBean {
public void listenPost(@Observes Post post) {
     System.out.println("Received : " + evt.message());
}
}
EVENTS CAN BE QUALIFIED
public class FirstBean {
@Inject Event<Post> postEvent;
public void saveNewPost(Post myPost) {
postEvent.select(
new AnnotationLiteral()<French> {}).fire(myPost);
}
}
public class SecondBean {
// these 3 observers will be called
public void listenFrPost(@Observes @French Post post) {}
public void listenPost(@Observes Post post) {}
public void listenObject(@Observes Object obj) {}
// This one won’t be called
public void listenEnPost(@Observes @English Post post) {}
}
AS ALWAYS “NOTYPE ERASURE”
public class SecondBean {
// these observers will be resolved depending
// on parameter in event payload type
public void listenStrPost(@Observes Post<String> post) {}
public void listenNumPost(@Observes Post<Number> post) {}
}
SOME BUILT-IN EVENTS
public class SecondBean {
public void beginRequest(@Observes @Initialized(RequestScoped.class)
ServletRequest req) {}
public void endRequest(@Observes @Destroyed(RequestScoped.class)
ServletRequest req) {}
public void beginSession(@Observes @Initialized(SessionScoped.class)
HttpSession session) {}
public void endSession(@Observes @Destroyed(SessionScoped.class)
HttpSession session) {}
}
DECORATORS & INTERCEPTORS
INTERCEPTORVS DECORATOR
• They are two Aspect Oriented mechanism
• Interceptor is technical oriented : transaction, security, logging
• Interceptor can be bound to any bean or bean method
• Decorator is business oriented : change the behaviour of a bean
• Decorator is for a given bean class
DECORATOR
• To use a decorator, your bean should implement an interface
• The decorator will implement the same interface and will be annotated
with @Decorator annotation
• It can be an abstract class (to avoid choosing methods to decorate)
• A decorator injects the bean it decorates with @Delegate annotation
A DECORATOR
@Decorator
@Priority(Interceptor.Priority.APPLICATION)
public abstract class HelloDecorator implements HelloService {
// The decorated service may be restricted with qualifiers
    @Inject @Delegate HelloService service;
    public String hello() {
        return service.hello() + "-decorated";
    }
}
INTERCEPTOR
Interceptor Binding Annotation
Interceptor Class
+
INTERCEPTOR BINDING…
@InterceptorBinding
@Target({METHOD, TYPE})
@Retention(RUNTIME)
public @interface Loggable {}
…IS USEDTO BIND AN INTERCEPTOR
@Interceptor @Loggable
@Priority(Interceptor.Priority.APPLICATION)
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());
        }
    }
}
IT CAN BE PUT ON CLASS OR METHOD
@Loggable
public class MyBean {
    @Inject HelloService service;
    public void displayHello() {
        display( service.hello();
    }
}
OTHER FEATURES
• Stereotypes: to create annotation gathering multiple annotations
• Alternatives: to provide alternative to a bean for tests or specific
environments
• Specialization : to completely override an existing bean
• Check the spec on http://cdi-spec.org
THAT’S ALL FOR BASIC CDI
• If you want to learn advanced stuff come to check my over talk : CDI
advanced.
• follow @cdispec and @antoine_sd on twitter
• Questions ?

Contenu connexe

Tendances

Eclipse_Building_Blocks
Eclipse_Building_BlocksEclipse_Building_Blocks
Eclipse_Building_BlocksRahul Shukla
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Maintaining a dependency graph with weaver
Maintaining a dependency graph with weaverMaintaining a dependency graph with weaver
Maintaining a dependency graph with weaverScribd
 
Ee java lab assignment 4
Ee java lab assignment 4Ee java lab assignment 4
Ee java lab assignment 4Kuntal Bhowmick
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 javatwo2011
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit7mind
 
MAX 2008 - Building your 1st AIR application
MAX 2008 - Building your 1st AIR applicationMAX 2008 - Building your 1st AIR application
MAX 2008 - Building your 1st AIR applicationrtretola
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection7mind
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with codekamal kotecha
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDiego Lewin
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierHimel Nag Rana
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02rhemsolutions
 
Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)njbartlett
 
It's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyIt's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyThiago “Fred” Porciúncula
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New FeaturesAli BAKAN
 
Using the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentSchalk Cronjé
 
AOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java PlatformAOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java PlatformPeter Pilgrim
 

Tendances (20)

Eclipse_Building_Blocks
Eclipse_Building_BlocksEclipse_Building_Blocks
Eclipse_Building_Blocks
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Maintaining a dependency graph with weaver
Maintaining a dependency graph with weaverMaintaining a dependency graph with weaver
Maintaining a dependency graph with weaver
 
Ee java lab assignment 4
Ee java lab assignment 4Ee java lab assignment 4
Ee java lab assignment 4
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望 Java EE 與 雲端運算的展望
Java EE 與 雲端運算的展望
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Hyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkitHyper-pragmatic Pure FP testing with distage-testkit
Hyper-pragmatic Pure FP testing with distage-testkit
 
MAX 2008 - Building your 1st AIR application
MAX 2008 - Building your 1st AIR applicationMAX 2008 - Building your 1st AIR application
MAX 2008 - Building your 1st AIR application
 
ScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency InjectionScalaUA - distage: Staged Dependency Injection
ScalaUA - distage: Staged Dependency Injection
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
Create Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien PotencierCreate Your Own Framework by Fabien Potencier
Create Your Own Framework by Fabien Potencier
 
Basics of Spring - KNOWARTH
Basics of Spring - KNOWARTHBasics of Spring - KNOWARTH
Basics of Spring - KNOWARTH
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)
 
It's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journeyIt's complicated, but it doesn't have to be: a Dagger journey
It's complicated, but it doesn't have to be: a Dagger journey
 
Java 9 New Features
Java 9 New FeaturesJava 9 New Features
Java 9 New Features
 
Using the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM DevelopmentUsing the Groovy Ecosystem for Rapid JVM Development
Using the Groovy Ecosystem for Rapid JVM Development
 
AOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java PlatformAOTB2014: Agile Testing on the Java Platform
AOTB2014: Agile Testing on the Java Platform
 

Similaire à Introduction to CDI

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-DurandSOAT
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzgKristijan Jurković
 
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 AngularJSShekhar Gulati
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveAndré Oriani
 
Using Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformUsing Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformArun Gupta
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCaelum
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Ray Ploski
 
Extending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss ForgeExtending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss ForgeAntoine Sabot-Durand
 
Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum
 
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 EcosystemSpark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 EcosystemArun Gupta
 
Quick Start to iOS Development
Quick Start to iOS DevelopmentQuick Start to iOS Development
Quick Start to iOS DevelopmentJussi Pohjolainen
 

Similaire à Introduction to CDI (20)

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
 
Introduction to CDI
Introduction to CDIIntroduction to CDI
Introduction to CDI
 
Building maintainable app #droidconzg
Building maintainable app #droidconzgBuilding maintainable app #droidconzg
Building maintainable app #droidconzg
 
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
 
Building maintainable app
Building maintainable appBuilding maintainable app
Building maintainable app
 
S313937 cdi dochez
S313937 cdi dochezS313937 cdi dochez
S313937 cdi dochez
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
 
Using Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 PlatformUsing Contexts & Dependency Injection in the Java EE 6 Platform
Using Contexts & Dependency Injection in the Java EE 6 Platform
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
CDI in JEE6
CDI in JEE6CDI in JEE6
CDI in JEE6
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6Introduction to CDI and DI in Java EE 6
Introduction to CDI and DI in Java EE 6
 
Extending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss ForgeExtending Java EE with CDI and JBoss Forge
Extending Java EE with CDI and JBoss Forge
 
Weapons for Boilerplate Destruction
Weapons for Boilerplate DestructionWeapons for Boilerplate Destruction
Weapons for Boilerplate Destruction
 
VRaptor 4 - JavaOne
VRaptor 4 - JavaOneVRaptor 4 - JavaOne
VRaptor 4 - JavaOne
 
Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan KustInfinum Android Talks #17 - Testing your Android applications by Ivan Kust
Infinum Android Talks #17 - Testing your Android applications by Ivan Kust
 
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 EcosystemSpark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
Spark IT 2011 - Context & Dependency Injection in the Java EE 6 Ecosystem
 
Quick Start to iOS Development
Quick Start to iOS DevelopmentQuick Start to iOS Development
Quick Start to iOS Development
 
Bean Intro
Bean IntroBean Intro
Bean Intro
 

Plus de Virtual JBoss User Group

Plus de Virtual JBoss User Group (11)

An Enterprise Developer's Joerney to the IoT
An Enterprise Developer's Joerney to the IoTAn Enterprise Developer's Joerney to the IoT
An Enterprise Developer's Joerney to the IoT
 
Messaging for IoT
Messaging for IoTMessaging for IoT
Messaging for IoT
 
Apache Lucene for Java EE Developers
Apache Lucene for Java EE DevelopersApache Lucene for Java EE Developers
Apache Lucene for Java EE Developers
 
What's New in WildFly 9?
What's New in WildFly 9?What's New in WildFly 9?
What's New in WildFly 9?
 
Narayana 5: The premier open source transaction manager
Narayana 5: The premier open source transaction manager Narayana 5: The premier open source transaction manager
Narayana 5: The premier open source transaction manager
 
Hacking on WildFly 9
Hacking on WildFly 9Hacking on WildFly 9
Hacking on WildFly 9
 
Implementing your own Google App Engine
Implementing your own Google App Engine Implementing your own Google App Engine
Implementing your own Google App Engine
 
Apache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI ToolboxApache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI Toolbox
 
Ceylon From Here to Infinity: The Big Picture and What's Coming
Ceylon From Here to Infinity: The Big Picture and What's Coming Ceylon From Here to Infinity: The Big Picture and What's Coming
Ceylon From Here to Infinity: The Big Picture and What's Coming
 
Going Further with CDI 1.2
Going Further with CDI 1.2Going Further with CDI 1.2
Going Further with CDI 1.2
 
Testing the Enterprise layers, with Arquillian
Testing the Enterprise layers, with ArquillianTesting the Enterprise layers, with Arquillian
Testing the Enterprise layers, with Arquillian
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Dernier (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Introduction to CDI

  • 1. INTRODUCTIONTO CONTEXTS AND DEPENDENCY INJECTION (CDI) @antoine_sd
  • 2. ANTOINE SABOT-DURAND • Senior Software Engineer @Red Hat • Java & OSS : • CDI co-spec lead • CDI community development • Tech Lead on Agorava • @antoine_sd
  • 3. WHAT IS CDI ? • Java EE dependency injection standard • Strong typed and type safe • Context management • Observer pattern included (Event bus) • Highly extensible
  • 4. A BIT OF HISTORY Dec 2009 June 2013 Apr 2014 Sep 2014 CDI 1.0 (Java EE 6) CDI 1.1 (Java EE 7) CDI 1.2 (1.1 MR) CDI 2.0 Starts Q1 2016 CDI 2.0 released
  • 5. IMPLEMENTATIONS JBoss Weld (Reference Implementation) Apache Open WebBeans
  • 6. CDI ACTIVATION • In CDI 1.0, you must add a beans.xml file to your archive • Since CDI 1.1, it’s activated by default: • All classes having a “bean defining annotation” become a bean • You can still use beans.xml file to activate CDI explicitly or deactivate it
  • 7. THE CDI BEAN • In Java EE 6 and 7 everything is a Bean including (EJB session beans) • 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. THIS IS A BEAN public class HelloService {     public String hello() {         return "Hello World!";     } }
  • 10. DI IN CONSTRUCTOR public class MyBean {     private HelloService service;     @Inject     public MyBean(HelloService service) {         this.service = service;     } }
  • 11. DI IN INITIALISER METHOD public class MyBean {     private HelloService service;     @Inject     public void initService(HelloService service) {         this.service = service;     } }
  • 12. DI IN FIELD public class MyBean {      @Inject private HelloService service;     public void displayHello() {         display(service.hello();     } }
  • 13. NOTYPE ERASURE IN CDI public class MyBean {     @Inject Service<User> userService; @Inject Service<Staff> staffService;      }
  • 14. NOTYPE ERASURE IN CDI public class MyBean {     @Inject Service<User> userService; @Inject Service<Staff> staffService;      } This works
  • 15. TYPES OF A BEAN • A bean will be a candidate for all “injection point” whose type belongs to its types set • Bean types set contains its type, all its implementing interfaces and all its ancestors including Object. • Bean types can be restricted by using @Typed annotation (Object is always in the set)
  • 16. TYPES OF A BEAN public class HelloService {
 //Types set : HelloService, Object
 }
 
 public class FrenchHelloService extends GenericService implements HelloService {
 //Types set : FrenchHelloService, GenericService, HelloService, Object 
 }
 
 @Typed({HelloService.class,GenericService.class})
 public class FrenchHelloService extends GenericService implements HelloService {
 //Types set : GenericService, HelloService, Object 
 }
  • 18. TWO SERVICE IMPLEMENTATIONS… 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!";     } }
  • 19. …NEED QUALIFIERS… @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface French {} @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface English {}
  • 20. …TO BE DISTINGUISHED. @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!";     } }
  • 21. QUALIFIED INJECTION POINTS 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();     } }
  • 22. QUALIFIERS CAN HAVE MEMBERS @Qualifier @Retention(RUNTIME) @Target({FIELD, TYPE, METHOD, PARAMETER}) public @interface Language {     Languages value(); @Nonbinding String description() default "";     public enum Languages {         FRENCH, ENGLISH     } }
  • 23. QUALIFIERS WITH MEMBERS 1/2 @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!";     } }
  • 24. QUALIFIERS WITH MEMBERS 2/2 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();     } }
  • 25. MULTIPLE QUALIFIERS public class MyBean {     @Inject @French HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  • 26. MULTIPLE QUALIFIERS public class MyBean {     @Inject @French @Console HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  • 27. MULTIPLE QUALIFIERS public class MyBean {     @Inject @French @Console @Secured HelloService service; } @French @Console @Secured public class FrenchHelloService implements HelloService { }
  • 28. MULTIPLE QUALIFIERS public class MyBean {     @Inject @French @Console @Secured HelloService service; } @French @Secured public class FrenchHelloService implements HelloService { }
  • 29. MULTIPLE QUALIFIERS public class MyBean {     @Inject @French @Console @Secured HelloService service; } @French @Secured public class FrenchHelloService implements HelloService { }
  • 32. SOMETIMES CALLED “LAZY INJECTION” public class MyBean {     @Inject Instance<HelloService> service;     public void displayHello() {         display( service.get().hello() );     } }
  • 33. CHECK BEAN EXISTENCE AT RUNTIME public class MyBean {     @Inject Instance<HelloService> service;     public void displayHello() {         if (!service.isUnsatisfied()) {             display( service.get().hello() );         }     } }
  • 34. LOOP ON ALL BEANS OF A GIVENTYPE public class MyBean {     @Inject @Any Instance<HelloService> services;     public void displayHello() {         for (HelloService service : services) {             display( service.hello() );         }     } }
  • 35. SELECT A QUALIFIER AT RUNTIME public class MyBean {     @Inject @Any Instance<HelloService> services;     public void displayHello() {         display(             service.select( new AnnotationLiteral()<French> {})                 .get() );     } }
  • 37. CONTEXTS MANAGE BEANS LIFECYCLE • They helps container to choose when a bean should be instantiated and destroyed • They enforce the fact that a given bean is a singleton for a given context • Built-in CDI contexts : • @Dependent (default) • @ApplicationScoped, @SessionScoped, @RequestScoped • @ConversationScoped • @Singleton • You can create your own scope
  • 38. CHOOSINGTHE RIGHT CONTEXT @SessionScoped public class CartBean {     public void addItem(Item item) { ...     } }
  • 39. CHOOSINGTHE RIGHT CONTEXT @ApplicationScoped public class CartBean {     public void addItem(Item item) { ...     } }
  • 40. CHOOSINGTHE RIGHT CONTEXT @ApplicationScoped public class CartBean {     public void addItem(Item item) { ...     } } FAIL !!!
  • 41. CONVERSATION IS MANAGE BY DEV @ConversationScoped public class CartBean {     public void addItem(Item item) { ...     } }
  • 42. NEW CONTEXTS CAN BE CREATED @ThreadScoped public class CartBean {     public void addItem(Item item) { ...     } }
  • 44. CREATING BEAN FROM ANY CLASS @Produces public MyNonCDIClass myProducer() { return new MyNonCdiClass(); } ... @Inject MyNonCDIClass bean;
  • 45. DISPOSER ARE OPTIONAL @Produces public MyNonCDIClass myProducer() { return new MyNonCdiClass(); } // Will be call at the instance end of life public void releaseMyInstance(@Disposes MyNonCdiClass inst) { inst.clean(); }
  • 46. PRODUCERS MAY HAVE A SCOPE @Produces @RequestScoped public FacesContext produceFacesContext() { return FacesContext.getCurrentInstance(); }
  • 47. GETTING INFO FROM INJECTION POINT @Produces public Logger produceLog(InjectionPoint injectionPoint) { return Logger.getLogger(injectionPoint.getMember() .getDeclaringClass().getName()); }
  • 48. REMEMBER :“NOTYPE ERASURE” @Produces
 public <K, V> Map<K, V> produceMap(InjectionPoint ip) {
 if (valueIsNumber(ip.getType())) {
 return new TreeMap<K, V>();
 }
 return new HashMap<K, V>();
 }
  • 50. A NICE WAYTO ADD DECOUPLING public class FirstBean { @Inject Event<Post> postEvent; public void saveNewPost(Post myPost) { postEvent.fire(myPost); } } public class SecondBean { public void listenPost(@Observes Post post) {      System.out.println("Received : " + evt.message()); } }
  • 51. EVENTS CAN BE QUALIFIED public class FirstBean { @Inject Event<Post> postEvent; public void saveNewPost(Post myPost) { postEvent.select( new AnnotationLiteral()<French> {}).fire(myPost); } } public class SecondBean { // these 3 observers will be called public void listenFrPost(@Observes @French Post post) {} public void listenPost(@Observes Post post) {} public void listenObject(@Observes Object obj) {} // This one won’t be called public void listenEnPost(@Observes @English Post post) {} }
  • 52. AS ALWAYS “NOTYPE ERASURE” public class SecondBean { // these observers will be resolved depending // on parameter in event payload type public void listenStrPost(@Observes Post<String> post) {} public void listenNumPost(@Observes Post<Number> post) {} }
  • 53. SOME BUILT-IN EVENTS public class SecondBean { public void beginRequest(@Observes @Initialized(RequestScoped.class) ServletRequest req) {} public void endRequest(@Observes @Destroyed(RequestScoped.class) ServletRequest req) {} public void beginSession(@Observes @Initialized(SessionScoped.class) HttpSession session) {} public void endSession(@Observes @Destroyed(SessionScoped.class) HttpSession session) {} }
  • 55. INTERCEPTORVS DECORATOR • They are two Aspect Oriented mechanism • Interceptor is technical oriented : transaction, security, logging • Interceptor can be bound to any bean or bean method • Decorator is business oriented : change the behaviour of a bean • Decorator is for a given bean class
  • 56. DECORATOR • To use a decorator, your bean should implement an interface • The decorator will implement the same interface and will be annotated with @Decorator annotation • It can be an abstract class (to avoid choosing methods to decorate) • A decorator injects the bean it decorates with @Delegate annotation
  • 57. A DECORATOR @Decorator @Priority(Interceptor.Priority.APPLICATION) public abstract class HelloDecorator implements HelloService { // The decorated service may be restricted with qualifiers     @Inject @Delegate HelloService service;     public String hello() {         return service.hello() + "-decorated";     } }
  • 60. …IS USEDTO BIND AN INTERCEPTOR @Interceptor @Loggable @Priority(Interceptor.Priority.APPLICATION) 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());         }     } }
  • 61. IT CAN BE PUT ON CLASS OR METHOD @Loggable public class MyBean {     @Inject HelloService service;     public void displayHello() {         display( service.hello();     } }
  • 62. OTHER FEATURES • Stereotypes: to create annotation gathering multiple annotations • Alternatives: to provide alternative to a bean for tests or specific environments • Specialization : to completely override an existing bean • Check the spec on http://cdi-spec.org
  • 63. THAT’S ALL FOR BASIC CDI • If you want to learn advanced stuff come to check my over talk : CDI advanced. • follow @cdispec and @antoine_sd on twitter • Questions ?