SlideShare une entreprise Scribd logo
1  sur  54
Télécharger pour lire hors ligne
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

Contenu connexe

Similaire à 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
 

Similaire à 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
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Dernier (20)

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...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech 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
 
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
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

Conhecendo CDI