SlideShare une entreprise Scribd logo
1  sur  19
CDI Contexts and Dependency Injection CDI, formerly known as JSR 299, is an attempt at describing a true standard on Dependency Injection.
Introduction CDI is the Java standard for dependency injection (DI) and interception (AOP).  CDI is similar to core Spring and Guice frameworks. Like JPA did for ORM, CDI simplifies and sanitizes the API for DI and AOP.
CDI to manage the dependencies CDI needs an bean.xml file to be in META-INF of your jar file or classpath or WEB-INF of your web application. This file can be completely empty. Use the @Inject annotation to annotate a setXXXsetter method in injected class
@Inject By default, CDI would look for a class that implements the ATMTransport interface, once it finds this it creates an instance and injects this instance of ATMTransport using the setter method setTransport. If we only had one possible instance of ATMTransport in our classpath, we would not need to annotate any of the ATMTransport implementations. Since we have three, namely, StandardAtmTransport, SoapAtmTransport, and JsonAtmTransport, we need to mark two of them as @Alternatives and one as @Default.  public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {                private ATMTransport transport;        @Inject        public void setTransport(ATMTransport transport) {                this.transport = transport;        }      } Using @Inject to inject via constructor args and fields @Inject public AutomatedTellerMachineImpl(ATMTransport transport) {                this.transport = transport;}
@Default and @Alternative Use the @Default annotation to annotate the StandardAtmTransport @Defaultpublic class StandardAtmTransport implements ATMTransport{ Use the @Alternative to annotate the SoapAtmTransport, and JsonRestAtmTransport. @Alternativepublic class JsonRestAtmTransport implements ATMTransport {
@Named The @Named annotation is used by JEE 6 application to make the bean accessible via the Unified EL (EL stands for Expression language and it gets used by JSPs and JSF components). @Named("atm")public class AutomatedTellerMachineImpl implements AutomatedTellerMachine{ It should be noted that if you use the @Named annotations and don't provide a name, then the name is the name of the class with the first letter lower case so this: makes the name automatedTellerMachineImpl.
@Produces Instead of relying on a constructor, you can delegate to a factory class to create the instance. To do this with CDI, you would use the @Produces from your factory class as follows: public class TransportFactory{                        @Produces ATMTransportcreateTransport() {                System.out.println("ATMTransport created with producer");                return new StandardAtmTransport();        }} On calling @Inject   private ATMTransport transport; it calls the factory method.
Defining @Alternative  The @Alternative CDI annotation allows you to have multiple matching dependencies for a given injection point. This means you can define beans that provide implementations for the same interface without worrying about ambigious dependency errors. When you mark a class with the @Alternative annotation, it is effectively disabled and cannot be considered for injection. The only exception is for the class that is defined in the beans.xml configuration file.  <beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/beans_1_0.xsd">         <alternatives>                <class>org.cdi.advocacy.JsonRestAtmTransport    </class>        </alternatives> </beans> Once this bean is identified, it is then used in any injection point that matches for this bean. No other beans for similar injection points can be declared as the ‘active’ alternative.
@Qualifier All objects and producers in CDI have qualifiers. If you do not assign a qaulifier it by default has the qualifier @Default and @Any. You may decide that at times you want to inject Soap or Json or the Standard transport. You don't want to list them as an alternative. Qualifiers can be used to discriminate exaclty what gets injected. You can write custom qualifiers.  @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER})public @interface Soap {} @Soappublic class SoapAtmTransport implements ATMTransport {
Injecting SoapAtmTransport using new @Soap qualifier via constructor arg @Inject public AutomatedTellerMachineImpl(@Soap ATMTransport transport) {                this.transport = transport;        } OR @Inject @Soapprivate ATMTransport transport;
Class uses two qualifiers @SuperFast @StandardFrameRelaySwitchingFlubberpublic class SuperFastAtmTransport implements ATMTransport {        public void communicateWithBank(byte[] datapacket) {                System.out.println("communicating with bank via the Super Fast transport " );        }} Usage : @Inject @SuperFast @StandardFrameRelaySwitchingFlubberprivate ATMTransport transport;
To solve Explosion of Qualifiers CDI allows you to discriminate on members of a qualifier to reduce the explosion of qualifiers. Instead of having three qualifier you could have one qualifier and an enum. Then if you need more types of transports, you only have to add an enum value instead of another class.  Let's demonstrate how this works by creating a new qualifier annotation called Transport. The Transport qualifier annotation will have a single member, an enum called type. The type member will be an new enum that we define called TransportType.  @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER})public @interface Transport {        TransportType type() default TransportType.STANDARD;} public enumTransportType {        JSON, SOAP, STANDARD;} Usage :  @Transport(type=TransportType.SOAP)public class SoapAtmTransport implements ATMTransport {  @Inject @Transport(type=TransportType.STANDARD)private ATMTransport transport;
Advanced: Using @Produces and InjectionPoint @Inject @TransportConfig(retries=2)private ATMTransport transport; @Produces ATMTransportcreateTransport(InjectionPointinjectionPoint) {                 Bean<?> bean = injectionPoint.getBean();TransportConfigtransportConfig = Bean.getBeanClass().getAnnotation (TransportConfig.class);StandardAtmTransport transport = new StandardAtmTransport();                transport.setRetries(transportConfig.retries());return transport; }
@Nonbinding Using @Nonbinding to combine a configuration annotation and a qualifier annotation into one annotation For e.g. - Transport qualifier annotation using @Nonbinding to add configuration retries param.
@Any @Any finds all of the transports in the system.  Once you inject the instances into the system, you can use the select method of instance to query for a particular type.  @Inject @Any private Instance<ATMTransport> allTransports; @PostConstruct        protected void init() {                transport = allTransports.select(new AnnotationLiteral<Default>(){}).get();                                if (transport!=null) {                        System.out.println("Found standard transport");                        return;                }                                transport = allTransports.select(new AnnotationLiteral<Json>(){}).get();                                if (transport!=null) {                        System.out.println("Found JSON standard transport");                        return;                }                                transport = allTransports.select(new AnnotationLiteral<Soap>(){}).get();                                                if (transport!=null) {                        System.out.println("Found SOAP standard transport");                        return;                }}
@Decorator Java EE 6 lets us create decorators through CDI, as part of their AOP features. If we want to implement cross cutting concerns that are still close enough to the business, we can use this feature of Java EE 6. @Decorator public class TicketServiceDecorator implements TicketService {  	@Inject @Delegate private TicketServiceticketService;  	@Inject private CateringServicecateringService;  	@Override public Ticket orderTicket(String name) {  		Ticket ticket = ticketService.orderTicket(name); cateringService.orderCatering(ticket); return ticket;  	} }
Injecting Java EE resources into a bean All managed beans may take advantage of Java EE component environment injection using @Resource, @EJB, @PersistenceContext, @PeristenceUnit, @PostConstruct and @PreDestroy and @WebServiceRef. Example : @Transactional @Interceptor public class TransactionInterceptor {    @Resource UserTransaction transaction;     @AroundInvoke public Object manageTransaction(InvocationContext ctx) throws Exception { ... } } @SessionScopedpublic class Login implements Serializable {     @Inject Credentials credentials;    @PersistenceContext EntityManager userDatabase;     }
Dirty truth CDI is part of JEE 6. It could easily be used outside of a JEE 6 container. The problem is that there is no standard interface to use CDI outside of a JEE 6 container so the three main implementations Caucho Resin Candi, Red Hat JBoss Weld and Apache OpenWebBeans all have their own way to run a CDI container standalone.
Conclusion Dependency Injection (DI) refers to the process of supplying an external dependency to a software component.  CDI is the Java standard for dependency injection and interception (AOP). It is evident from the popularity of DI and AOP that Java needs to address DI and AOP so that it can build other standards on top of it. DI and AOP are the foundation of many Java frameworks.

Contenu connexe

Tendances

Tendances (20)

The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
 
Java annotations
Java annotationsJava annotations
Java annotations
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
 
Spring training
Spring trainingSpring training
Spring training
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 
An Overview of Project Jigsaw
An Overview of Project JigsawAn Overview of Project Jigsaw
An Overview of Project Jigsaw
 
Java RMI
Java RMIJava RMI
Java RMI
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Java Beans
Java BeansJava Beans
Java Beans
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification Questions
 
Functional programming
Functional programmingFunctional programming
Functional programming
 

Similaire à J2ee standards > CDI

documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSam Brannen
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2Techglyphs
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2wiradikusuma
 
quickguide-einnovator-2-spring4-dependency-injection-annotations
quickguide-einnovator-2-spring4-dependency-injection-annotationsquickguide-einnovator-2-spring4-dependency-injection-annotations
quickguide-einnovator-2-spring4-dependency-injection-annotationsjorgesimao71
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentalsjavaease
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with KotlinRapidValue
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's NewTed Pennings
 

Similaire à J2ee standards > CDI (20)

documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
quickguide-einnovator-2-spring4-dependency-injection-annotations
quickguide-einnovator-2-spring4-dependency-injection-annotationsquickguide-einnovator-2-spring4-dependency-injection-annotations
quickguide-einnovator-2-spring4-dependency-injection-annotations
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Smart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdfSmart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdf
 
Smart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdfSmart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdf
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
Riding Apache Camel
Riding Apache CamelRiding Apache Camel
Riding Apache Camel
 
J Unit
J UnitJ Unit
J Unit
 
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with Kotlin
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 

Dernier

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Dernier (20)

DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

J2ee standards > CDI

  • 1. CDI Contexts and Dependency Injection CDI, formerly known as JSR 299, is an attempt at describing a true standard on Dependency Injection.
  • 2. Introduction CDI is the Java standard for dependency injection (DI) and interception (AOP). CDI is similar to core Spring and Guice frameworks. Like JPA did for ORM, CDI simplifies and sanitizes the API for DI and AOP.
  • 3. CDI to manage the dependencies CDI needs an bean.xml file to be in META-INF of your jar file or classpath or WEB-INF of your web application. This file can be completely empty. Use the @Inject annotation to annotate a setXXXsetter method in injected class
  • 4. @Inject By default, CDI would look for a class that implements the ATMTransport interface, once it finds this it creates an instance and injects this instance of ATMTransport using the setter method setTransport. If we only had one possible instance of ATMTransport in our classpath, we would not need to annotate any of the ATMTransport implementations. Since we have three, namely, StandardAtmTransport, SoapAtmTransport, and JsonAtmTransport, we need to mark two of them as @Alternatives and one as @Default. public class AutomatedTellerMachineImpl implements AutomatedTellerMachine {                private ATMTransport transport;        @Inject        public void setTransport(ATMTransport transport) {                this.transport = transport;        }      } Using @Inject to inject via constructor args and fields @Inject public AutomatedTellerMachineImpl(ATMTransport transport) {                this.transport = transport;}
  • 5. @Default and @Alternative Use the @Default annotation to annotate the StandardAtmTransport @Defaultpublic class StandardAtmTransport implements ATMTransport{ Use the @Alternative to annotate the SoapAtmTransport, and JsonRestAtmTransport. @Alternativepublic class JsonRestAtmTransport implements ATMTransport {
  • 6. @Named The @Named annotation is used by JEE 6 application to make the bean accessible via the Unified EL (EL stands for Expression language and it gets used by JSPs and JSF components). @Named("atm")public class AutomatedTellerMachineImpl implements AutomatedTellerMachine{ It should be noted that if you use the @Named annotations and don't provide a name, then the name is the name of the class with the first letter lower case so this: makes the name automatedTellerMachineImpl.
  • 7. @Produces Instead of relying on a constructor, you can delegate to a factory class to create the instance. To do this with CDI, you would use the @Produces from your factory class as follows: public class TransportFactory{                        @Produces ATMTransportcreateTransport() {                System.out.println("ATMTransport created with producer");                return new StandardAtmTransport();        }} On calling @Inject   private ATMTransport transport; it calls the factory method.
  • 8. Defining @Alternative The @Alternative CDI annotation allows you to have multiple matching dependencies for a given injection point. This means you can define beans that provide implementations for the same interface without worrying about ambigious dependency errors. When you mark a class with the @Alternative annotation, it is effectively disabled and cannot be considered for injection. The only exception is for the class that is defined in the beans.xml configuration file. <beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/beans_1_0.xsd">         <alternatives>                <class>org.cdi.advocacy.JsonRestAtmTransport </class>        </alternatives> </beans> Once this bean is identified, it is then used in any injection point that matches for this bean. No other beans for similar injection points can be declared as the ‘active’ alternative.
  • 9. @Qualifier All objects and producers in CDI have qualifiers. If you do not assign a qaulifier it by default has the qualifier @Default and @Any. You may decide that at times you want to inject Soap or Json or the Standard transport. You don't want to list them as an alternative. Qualifiers can be used to discriminate exaclty what gets injected. You can write custom qualifiers. @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER})public @interface Soap {} @Soappublic class SoapAtmTransport implements ATMTransport {
  • 10. Injecting SoapAtmTransport using new @Soap qualifier via constructor arg @Inject public AutomatedTellerMachineImpl(@Soap ATMTransport transport) {                this.transport = transport;        } OR @Inject @Soapprivate ATMTransport transport;
  • 11. Class uses two qualifiers @SuperFast @StandardFrameRelaySwitchingFlubberpublic class SuperFastAtmTransport implements ATMTransport {        public void communicateWithBank(byte[] datapacket) {                System.out.println("communicating with bank via the Super Fast transport " );        }} Usage : @Inject @SuperFast @StandardFrameRelaySwitchingFlubberprivate ATMTransport transport;
  • 12. To solve Explosion of Qualifiers CDI allows you to discriminate on members of a qualifier to reduce the explosion of qualifiers. Instead of having three qualifier you could have one qualifier and an enum. Then if you need more types of transports, you only have to add an enum value instead of another class. Let's demonstrate how this works by creating a new qualifier annotation called Transport. The Transport qualifier annotation will have a single member, an enum called type. The type member will be an new enum that we define called TransportType. @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, FIELD, PARAMETER})public @interface Transport {        TransportType type() default TransportType.STANDARD;} public enumTransportType {        JSON, SOAP, STANDARD;} Usage : @Transport(type=TransportType.SOAP)public class SoapAtmTransport implements ATMTransport {  @Inject @Transport(type=TransportType.STANDARD)private ATMTransport transport;
  • 13. Advanced: Using @Produces and InjectionPoint @Inject @TransportConfig(retries=2)private ATMTransport transport; @Produces ATMTransportcreateTransport(InjectionPointinjectionPoint) {                 Bean<?> bean = injectionPoint.getBean();TransportConfigtransportConfig = Bean.getBeanClass().getAnnotation (TransportConfig.class);StandardAtmTransport transport = new StandardAtmTransport();                transport.setRetries(transportConfig.retries());return transport; }
  • 14. @Nonbinding Using @Nonbinding to combine a configuration annotation and a qualifier annotation into one annotation For e.g. - Transport qualifier annotation using @Nonbinding to add configuration retries param.
  • 15. @Any @Any finds all of the transports in the system. Once you inject the instances into the system, you can use the select method of instance to query for a particular type. @Inject @Any private Instance<ATMTransport> allTransports; @PostConstruct        protected void init() {                transport = allTransports.select(new AnnotationLiteral<Default>(){}).get();                                if (transport!=null) {                        System.out.println("Found standard transport");                        return;                }                                transport = allTransports.select(new AnnotationLiteral<Json>(){}).get();                                if (transport!=null) {                        System.out.println("Found JSON standard transport");                        return;                }                                transport = allTransports.select(new AnnotationLiteral<Soap>(){}).get();                                                if (transport!=null) {                        System.out.println("Found SOAP standard transport");                        return;                }}
  • 16. @Decorator Java EE 6 lets us create decorators through CDI, as part of their AOP features. If we want to implement cross cutting concerns that are still close enough to the business, we can use this feature of Java EE 6. @Decorator public class TicketServiceDecorator implements TicketService { @Inject @Delegate private TicketServiceticketService; @Inject private CateringServicecateringService; @Override public Ticket orderTicket(String name) { Ticket ticket = ticketService.orderTicket(name); cateringService.orderCatering(ticket); return ticket; } }
  • 17. Injecting Java EE resources into a bean All managed beans may take advantage of Java EE component environment injection using @Resource, @EJB, @PersistenceContext, @PeristenceUnit, @PostConstruct and @PreDestroy and @WebServiceRef. Example : @Transactional @Interceptor public class TransactionInterceptor {    @Resource UserTransaction transaction;    @AroundInvoke public Object manageTransaction(InvocationContext ctx) throws Exception { ... } } @SessionScopedpublic class Login implements Serializable {    @Inject Credentials credentials;    @PersistenceContext EntityManager userDatabase;     }
  • 18. Dirty truth CDI is part of JEE 6. It could easily be used outside of a JEE 6 container. The problem is that there is no standard interface to use CDI outside of a JEE 6 container so the three main implementations Caucho Resin Candi, Red Hat JBoss Weld and Apache OpenWebBeans all have their own way to run a CDI container standalone.
  • 19. Conclusion Dependency Injection (DI) refers to the process of supplying an external dependency to a software component. CDI is the Java standard for dependency injection and interception (AOP). It is evident from the popularity of DI and AOP that Java needs to address DI and AOP so that it can build other standards on top of it. DI and AOP are the foundation of many Java frameworks.