SlideShare una empresa de Scribd logo
1 de 54
Descargar para leer sin conexión
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

Más contenido relacionado

Similar a 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
 

Similar a 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
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

Conhecendo CDI