SlideShare a Scribd company logo
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.

More Related Content

What's hot

The definitive guide to java agents
The definitive guide to java agentsThe definitive guide to java agents
The definitive guide to java agents
Rafael Winterhalter
 
Monitoring distributed (micro-)services
Monitoring distributed (micro-)servicesMonitoring distributed (micro-)services
Monitoring distributed (micro-)services
Rafael Winterhalter
 
Java annotations
Java annotationsJava annotations
Java annotations
FAROOK Samath
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and BytecodeYoav Avrahami
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Getting started with Java 9 modules
Getting started with Java 9 modulesGetting started with Java 9 modules
Getting started with Java 9 modules
Rafael Winterhalter
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
Danairat Thanabodithammachari
 
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
Peter Antman
 
Spring training
Spring trainingSpring training
Spring training
TechFerry
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
Rafael Winterhalter
 
An Overview of Project Jigsaw
An Overview of Project JigsawAn Overview of Project Jigsaw
An Overview of Project Jigsaw
Rafael Winterhalter
 
Java RMI
Java RMIJava RMI
Java RMI
Ankit Desai
 
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
Rafael Winterhalter
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate IntroductionRanjan Kumar
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
Rafael Winterhalter
 
Java Beans
Java BeansJava Beans
Java Beans
Ankit Desai
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification Questions
SpringMockExams
 
Functional programming
Functional programmingFunctional programming
Functional programming
Lhouceine OUHAMZA
 

What's hot (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
 

Similar to 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 Support
Sam 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
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
Jaanus Pöial
 
Bt0083 server side programing 2
Bt0083 server side programing  2Bt0083 server side programing  2
Bt0083 server side programing 2
Techglyphs
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
wiradikusuma
 
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 java
ciklum_ods
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
Smart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdfSmart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdf
GayathriRHICETCSESTA
 
Smart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdfSmart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdf
GayathriRHICETCSESTA
 
ORM JPA
ORM JPAORM JPA
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
javaease
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
Serhii Kartashov
 
J Unit
J UnitJ Unit
Appium Automation with Kotlin
Appium Automation with KotlinAppium Automation with Kotlin
Appium Automation with Kotlin
RapidValue
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
Gurpreet singh
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's NewTed Pennings
 

Similar to 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 (1).pdf
Smart material - Unit 3 (1).pdfSmart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdf
 
Smart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdfSmart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).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
 

Recently uploaded

UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
danishmna97
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems S.M.S.A.
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
SOFTTECHHUB
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
Neo4j
 

Recently uploaded (20)

UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
How to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptxHow to Get CNIC Information System with Paksim Ga.pptx
How to Get CNIC Information System with Paksim Ga.pptx
 
Uni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdfUni Systems Copilot event_05062024_C.Vlachos.pdf
Uni Systems Copilot event_05062024_C.Vlachos.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
GraphSummit Singapore | Neo4j Product Vision & Roadmap - Q2 2024
 

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.