SlideShare ist ein Scribd-Unternehmen logo
1 von 54
Downloaden Sie, um offline zu lesen
Conhecendo CDI
CDI 1.1 - JSR 346
Daniel Cunha (soro)
danielsoro@gmail.com
http://www.danielsoro.com.br
Daniel Cunha

soro - irc.freenode.net
http://danielsoro.com.br
http://github.com/danielsoro
http://twitter.com/dvlc_
danielsoro@gmail.com
O que é e pra que
serve o CDI?
Iniciando com CDI
beans.xml
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http:
//xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
Injetando suas
dependências
@
Inject
E quando eu tenho
mais de uma
implementação?
Qualifiers
Alternatives
Alternatives
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http:
//xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
<alternatives>
<class>package.RelaxedItemValdidator</class>
</alternatives>
</beans>
@
Priority
Interceptor.Priority.PLATFORM_BEFORE = 0
Interceptor.Priority.LIBRARY_BEFORE = 1000
Interceptor.Priority.APPLICATION = 2000
Interceptor.Priority.LIBRARY_AFTER = 3000
Interceptor.Priority.PLATFORM_AFTER = 4000
E quando eu quiser
dar nome ao meu
bean?
@Inject @Named("user.name")
private String userName;
E quando eu quiser
evoluir o meu bean?
@Specializes
public class ClasseFilha extends ClasseMae
{}
@Specializes @Cejug
public class ClasseFilha extends ClasseMae
{}
@RequestScope @Ivia @Named(“mae”)
public class ClasseMae
@Specializes @Cejug
public class ClasseFilha extends ClasseMae
{}
@RequestScope @Ivia @Named(“mae”)
public class ClasseMae
@Specializes @Cejug @Named(“filha”)
public class ClasseFilha extends ClasseMae {}
Tenho outra forma de
evitar ambiguidade?
@Typed({Cejug.class,GUJavaSC.class})
public class BrazilJugs extends Jugs
{}
E quando eu quiser
injetar uma classe
que não é um bean
CDI?
import javax.enterprise.inject.Produces;
public class Produtor {
@Produces
public Logger criarLogger(){
return LoggerFactory.getLogger(ConhecendoCDI.class);
}
}
E quando eu quiser
finalizar esse bean?
import javax.enterprise.inject.Disposes;
public class Produtor {
@Produces @CejugDB
public EntityManager criaEntityManager(){
EntityManagerFactory emf = Persistence.
createEntityManagerFactory("cejugdb");
return emf.createEntityManager();
}
public void fechaEntityManager(@Dispose @CejugDB
EntityManager em){
em.close();
}
}
Criações mais
flexiveis
import javax.enterprise.inject.Produces;
public class Produtor {
@Produces
public Logger criarLogger(InjectPoint injectPoint){
return LoggerFactory.getLogger(injectPoint.getMember()
.getDeclaringClass().getName());
}
}
Escopos CDI
@RequestScoped
@SessionScoped
@ApplicationScoped
@ConversationScoped
@Dependent
Quero
interceptar..
Como eu faço?
@Interceptor @Priority(Interceptor.Priority.
APPLICATION)
public class Auditor {}
Posso escolher
quem interceptar?
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@InterceptorBinding
public @interface Auditavel {}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Inherited
@InterceptorBinding
public @interface Auditavel {}
Interceptando o
ciclo de vida
@AroundConstruct
@PostConstruct
@PreDestroy
Decorando o
nosso bean
@Decorator
public abstract class CoderDecorator implements Coder
{
@Inject
@Delegate
@Any
Coder coder;
public String codeString(String s, int tval) {
int len = s.length();
return coder.codeString(s, tval);
}
}
Decorator
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http:
//xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
<decorators>
<class>decorators.CoderDecorator</class>
</decorators>
</beans>
Preciso replicar as 30
annotation da classe
X na Y… e agora?
@Stereotype
import javax.enterprise.inject.Stereotype;
@Stereotype
@Named @RequestScoped
@Auditavel @Rastreavel
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CejugStereotype {
}
Diminuindo
acoplamento
@Inject
private Event<Palestrante> eventoCejug;
eventoCejug.fire(palestrante);
public void adicionarPalestrante(@Observes
Palestrante palestrante){}
E eu posso fazer
chamadas
assíncronas?
@Asynchronous
public void adicionarPalestrante(@Observes
Palestrante palestrante){}
Dúvidas?
Obrigado
Conhecendo CDI
CDI 1.1 - JSR 346
Daniel Cunha (soro)
danielsoro@gmail.com
http://www.danielsoro.com.br

Weitere ähnliche Inhalte

Ähnlich wie Conhecendo CDI

Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
Simon Willison
 
Testing - Selenium? Rich-Clients? Containers?
Testing - Selenium? Rich-Clients? Containers?Testing - Selenium? Rich-Clients? Containers?
Testing - Selenium? Rich-Clients? Containers?
Tobias Schneck
 
Sai devops - the art of being specializing generalist
Sai   devops - the art of being specializing generalistSai   devops - the art of being specializing generalist
Sai devops - the art of being specializing generalist
Odd-e
 

Ähnlich wie Conhecendo CDI (20)

Best practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on SalesforceBest practices for implementing CI/CD on Salesforce
Best practices for implementing CI/CD on Salesforce
 
MyFaces CODI and JBoss Seam3 become Apache DeltaSpike
MyFaces CODI and JBoss Seam3 become Apache DeltaSpikeMyFaces CODI and JBoss Seam3 become Apache DeltaSpike
MyFaces CODI and JBoss Seam3 become Apache DeltaSpike
 
Neo4j Stored Procedure Training Part 1
Neo4j Stored Procedure Training Part 1Neo4j Stored Procedure Training Part 1
Neo4j Stored Procedure Training Part 1
 
Useful practices of creation automatic tests by using cucumber jvm
Useful practices of creation automatic tests by using cucumber jvmUseful practices of creation automatic tests by using cucumber jvm
Useful practices of creation automatic tests by using cucumber jvm
 
Code Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application MigrationsCode Coverage for Total Security in Application Migrations
Code Coverage for Total Security in Application Migrations
 
Take control of your Jenkins jobs via job DSL.
Take control of your Jenkins jobs via job DSL.Take control of your Jenkins jobs via job DSL.
Take control of your Jenkins jobs via job DSL.
 
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...
AI&BigData Lab. Александр Конопко "Celos: оркестрирование и тестирование зада...
 
Building Things Fast - and getting approval
Building Things Fast - and getting approvalBuilding Things Fast - and getting approval
Building Things Fast - and getting approval
 
Testing - Selenium? Rich-Clients? Containers?
Testing - Selenium? Rich-Clients? Containers?Testing - Selenium? Rich-Clients? Containers?
Testing - Selenium? Rich-Clients? Containers?
 
Keeping Your DevOps Transformation From Crushing Your Ops Capacity
Keeping Your DevOps Transformation From Crushing Your Ops Capacity Keeping Your DevOps Transformation From Crushing Your Ops Capacity
Keeping Your DevOps Transformation From Crushing Your Ops Capacity
 
Sai devops - the art of being specializing generalist
Sai   devops - the art of being specializing generalistSai   devops - the art of being specializing generalist
Sai devops - the art of being specializing generalist
 
DevOps: The New Face Of Application Development - Global Azure Bootcamp
DevOps: The New Face Of Application Development - Global Azure BootcampDevOps: The New Face Of Application Development - Global Azure Bootcamp
DevOps: The New Face Of Application Development - Global Azure Bootcamp
 
Javaland 2017: "You´ll do microservices now". Now what?
Javaland 2017: "You´ll do microservices now". Now what?Javaland 2017: "You´ll do microservices now". Now what?
Javaland 2017: "You´ll do microservices now". Now what?
 
Fluentlenium Functional tests hang.pdf
Fluentlenium Functional tests hang.pdfFluentlenium Functional tests hang.pdf
Fluentlenium Functional tests hang.pdf
 
Chef vs Puppet vs Ansible vs SaltStack | Configuration Management Tools Compa...
Chef vs Puppet vs Ansible vs SaltStack | Configuration Management Tools Compa...Chef vs Puppet vs Ansible vs SaltStack | Configuration Management Tools Compa...
Chef vs Puppet vs Ansible vs SaltStack | Configuration Management Tools Compa...
 
Salesforce Apex Hours:-Mitigate with Mono-Purpose Microservices
Salesforce Apex Hours:-Mitigate with Mono-Purpose MicroservicesSalesforce Apex Hours:-Mitigate with Mono-Purpose Microservices
Salesforce Apex Hours:-Mitigate with Mono-Purpose Microservices
 
Expanding XPages with Bootstrap Plugins for Ultimate Usability
Expanding XPages with Bootstrap Plugins for Ultimate UsabilityExpanding XPages with Bootstrap Plugins for Ultimate Usability
Expanding XPages with Bootstrap Plugins for Ultimate Usability
 
Developing web applications in 2010
Developing web applications in 2010Developing web applications in 2010
Developing web applications in 2010
 
Fastest offline with SQLite
Fastest offline with SQLiteFastest offline with SQLite
Fastest offline with SQLite
 
Jenkins CI
Jenkins CIJenkins CI
Jenkins CI
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

Conhecendo CDI