SlideShare a Scribd company logo
CDIContexts and Dependency InjectionCDI, formerly known as JSR 299, is an attempt at describing a true standard on Dependency Injection.
IntroductionCDI 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 dependenciesCDI 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
@InjectBy 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 @AlternativeUse 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 {
@NamedThe @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.
@ProducesInstead 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.
@QualifierAll 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 QualifiersCDI 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;}
@NonbindingUsing @Nonbinding to combine a configuration annotation and a qualifier annotation into one annotationFor 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;                }}
@DecoratorJava 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 beanAll 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 truthCDI 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.
ConclusionDependency 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.
Ad

More Related Content

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
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 Bytecode
Yoav Avrahami
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
Carol McDonald
 
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
 
Designing Better API
Designing Better APIDesigning Better API
Designing Better API
Kaniska Mandal
 
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 Introduction
Ranjan 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
 

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...
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-annotations
jorgesimao71
 
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 (2).pdf
Smart material - Unit 3 (2).pdfSmart material - Unit 3 (2).pdf
Smart material - Unit 3 (2).pdf
GayathriRHICETCSESTA
 
Smart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdfSmart material - Unit 3 (1).pdf
Smart material - Unit 3 (1).pdf
GayathriRHICETCSESTA
 
ORM JPA
ORM JPAORM JPA
ORM JPA
Rody Middelkoop
 
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
 
Riding Apache Camel
Riding Apache CamelRiding Apache Camel
Riding Apache Camel
Apache Event Beijing
 
J Unit
J UnitJ Unit
J Unit
guest333f37c3
 
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 New
Ted Pennings
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
Rajiv Srivastava
 
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
 
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-annotations
jorgesimao71
 
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
 
Java oops and fundamentals
Java oops and fundamentalsJava oops and fundamentals
Java oops and fundamentals
javaease
 
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 New
Ted Pennings
 
Ad

Recently uploaded (20)

HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Ad

J2ee standards > CDI

  • 1. CDIContexts and Dependency InjectionCDI, formerly known as JSR 299, is an attempt at describing a true standard on Dependency Injection.
  • 2. IntroductionCDI 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 dependenciesCDI 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. @InjectBy 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 @AlternativeUse 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. @NamedThe @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. @ProducesInstead 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. @QualifierAll 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 QualifiersCDI 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. @NonbindingUsing @Nonbinding to combine a configuration annotation and a qualifier annotation into one annotationFor 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. @DecoratorJava 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 beanAll 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 truthCDI 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. ConclusionDependency 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.