SlideShare une entreprise Scribd logo
1  sur  45
Context & Dependency Injection
        from Java EE 6
           in Action
           Max Rydahl Andersen
                  Red Hat
       http://about.me/maxandersen

                14th April
        Miracle Open World 2011
About Me
•   Max Rydahl Andersen
•   Lead of JBoss Tools & Developer Studio
•   Committer on Hibernate Core, Seam & Weld
•   Co-host of JBoss Community Asylum Podcast
•   @maxandersen on Twitter
•   http://about.me/maxandersen
Today’s goal is to answer ..
Today’s goal is to answer ..

   Is JEE 6
  awesome ?
Agenda

•   What is new in Java EE 6 ?
•   Quick Intro to CDI
•   Deep-dive Example
    •   Solving real problems with EE 6
What is new in
 Java EE 6 ?
What is new in Java EE 6 ?
What is new in Java EE 6 ?

•   Forget everything bad you have seen or heard
    about Java EE, because...
•   ...it is highly simplified
•   ...it’s actually usable now
•   ...it Just Works!
Java EE 6: Goals

•Extensibility
   •Allow more components to be standalone (EJB 3.1)
•Profiles
   •Subsets of “full” EE platform
   •Web Profile
•Pruning
   •CMP, JAX-RPC, JAXR, JSR-88 are “pruned” in EE6
•Technology Improvements



   8                         Pete Muir
Java EE 6: Newcomers

•Managed Beans (part of JSR-316)
•Contexts and Dependency Injection - JSR-299
•Bean Validation - JSR-303
•JAX-RS (RESTful Web Services) - JSR-311




  9                     Pete Muir
Java EE 6: Notable Updates

•Servlet 3.0                             •JSF 2
   •Easier configuration                     •Ajax
•JPA 2.0                                    •Easy component creation
   •Type-safe Criteria API                  •Bookmarkable URLs
   •Extra mappings                          •Templating
•EJB 3.1




  10                         Pete Muir
Web Profile

•Persistence                      •Presentation
   •JPA 2.0                          •JSF 2.0
   •JTA                              •Servlet 3.0

•Component model
   •EJB 3.1 Lite
   •Bean Validation
   •CDI (JSR-299)




  11                  Pete Muir
Quick Intro to CDI
What is CDI ?
•   “...unify the JSF managed bean component
    model with the EJB component model,
    resulting in a significantly simplified
    programming model for web-based
    applications.” - JSR-299/Gavin King
•   “CDI simplifies and sanitizes the API for DI
    and AOP like JPA did for ORM” - CDI
    Tutorial/Rick Hightower
CDI Acronyms

•   The Spec - Context & Dependency Injection
    for JEE (CDI)
•   The Reference Implementation - Weld
•   Other implementations - CanDI (Resin),
    Open WebBeans (Apache)
The Simplest CDI Bean


public class Welcome {

 public String buildPhrase(String city) {

 
 return "Hello from " + city + "!";

 }
}
The Simplest Session Bean


@Stateless public class Welcome {

 public String buildPhrase(String city) {

 
 return "Hello from " + city + "!";

 }
}
Simplest CDI Packaging
Simplest CDI Packaging



     Can just be empty!
Dependency Injection
public class Greeter {


 Welcome w;


 public void welcome() {

 
 System.out.println(w.buildPhrase("Billund"));

 }
}
Dependency Injection
public class Greeter {

 @Inject

 Welcome w;


 public void welcome() {

 
 System.out.println(w.buildPhrase("Billund"));

 }
}
Another Implementation
public class TranslatingWelcome extends
Welcome {

    @Inject GoogleTranslator translator;

    public String buildPhrase(String city) {
      return translator.translate(
             "Welcome to " + city + "!");
    }
}
Quiz: What gets Injected ?

public class Greeter {

 @Inject

 Welcome w; // Welcome or TranslatingWelcome ?


 public void welcome() {

 
 System.out.println(w.buildPhrase("Billund"));

 }
}
Qualifiers to the rescue

  @Qualifier
  @Target({ TYPE, METHOD,
  PARAMETER, FIELD })
  @Retention(RUNTIME)
  @Documented
  public @interface Translating {

  }
Qualifiers to the rescue

@Translating
public class TranslatingWelcome extends Welcome {
  @Inject GoogleTranslator translator;

    public String buildPhrase(String city) {
      return translator.translate("Welcome to " + city + "!");
    }
}
Qualifiers to the rescue
@Translating
public class TranslatingWelcome extends Welcome {
  @Inject GoogleTranslator translator;

    public String buildPhrase(String city) {
      return translator.translate("Welcome to " + city + "!");
    }
}
Qualifiers to the rescue
@Translating
public class TranslatingWelcome extends Welcome {
  @Inject GoogleTranslator translator;

    public String buildPhrase(String city) {
      return translator.translate("Welcome to " + city + "!");
    }
                  public class Greeter {
}                 
 @Inject @Translating
                  
 Welcome w; // No ambigiuty!

                  
 public void welcome() {
                  
 
 System.out.println(w.buildPhrase("Billund"));
                  
 }
                  }
@Produces

public class WelcomeProducer {


 @Produces @Translating Welcome createWelcome() {

 
 return new TranslatingWelcome();

 }
}
Scopes

•   JEE 6 provides a set of Scopes
•   @Dependent, @ApplicationScoped,
    @RequestScoped, @SessionScoped,
    @ConversationScoped, <put your own here>
•   Each have a context which are managed by
    the container (you don’t have to do explicit
    cleanup)
More CDI

•   Event/Observers
•   Stereo Types
•   Alternatives
•   API for Framework Implementors
Deep-dive Example
•   PasteCode - part of the Weld Examples
•   Uses just Servlet, CDI, JSF & EJB’s
•   JEE 6 Web Profile
Challenges
•   Persistence
•   Validation of data from client to database
•   Configuration of Servlet’s, EJB’s etc.
•   Access to Beans from UI-Layer (EJB->JSF)
•   Dependency Injection for decoupling concerns
•   Setup things at Application Startup
•   Cross-cutting custom business concerns (example Flood Control)
•   Sending and receiving events
•   Batch job’s
•   ...and more
CDI Bean In Action
public class PasteWindow
{
  ...
       private CodeFragmentManager
codeFragmentManager;t


 public CodeFragment getCodeFragment()
 {
    return codeFragment;
 }
   …
CDI Bean In Action
@Named

public class PasteWindow
{
  ...
       private CodeFragmentManager
codeFragmentManager;t


 public CodeFragment getCodeFragment()
 {
    return codeFragment;
 }
   …
CDI Bean In Action
@Named
@RequestScoped
public class PasteWindow
{
  ...
       private CodeFragmentManager
codeFragmentManager;t


  public CodeFragment getCodeFragment()
  {
     return codeFragment;
  }
    …
CDI Bean In Action
@Named
@RequestScoped
public class PasteWindow
{
  ...
@Inject private CodeFragmentManager
codeFragmentManager;t


  public CodeFragment getCodeFragment()
  {
     return codeFragment;
  }
    …
Persistence/Validation
@Entity
public class CodeFragment {
  @Id
  @GeneratedValue(strategy = AUTO)
  @Column(name = "id")
  private int id;

    @Lob
    @Size(min=1,
        message="Must enter some text!")
    private String text;
    …
}
Application Startup
@Startup
@Singleton
public class PopulateDatabase {


 @PersistenceContext

 private EntityManager entityManager;

    @PostConstruct
    public void startup()
    {
      …
    }
}
Sending and receiving events
@Inject
private Event<CodeFragment> event;

...
event.fire(code);

public void
addEntry(@Observes CodeFragment codeFragment)
{
  this.log.add(codeFragment);
}
Cross-Cutting Business
@Decorator       w/Decoratorimplements
public abstract class FloodingDecorator
CodeFragmentManager, Serializable
{
  @Inject @Delegate
  private CodeFragmentManage codeFragmentManager;

  public String addCodeFragment(CodeFragment code,
boolean privateFragment)
  {
     ...
     return
codeFragmentManager.addCodeFragment(code,
privateFragment);
Summary
•   JSR-299 provides a set of services for Java EE
•   Bridges JSF and EJB
•   Offers loose coupling with strong typing
•   Extensive SPI for third-party integration with
    Java EE
•   Weld: JSR-299 Reference Implementation
•   Seam 3: Portable extensions for Java EE
Q &A ?
Q &A ?

 JEE 6 is
awesome!
Rate this talk: http://bit.ly/cdiaction
Q &A ?
•   Weld - http://seamframework.org/Weld
•   Seam 3 project - http://seamframework.org/Seam3
•   Weld Maven archetypes for CDI and Java EE - http://tinyurl.com/
    goweld
•   Weld reference guide - http://tinyurl.com/weld-reference-101
•   CDI JavaDoc - http://docs.jboss.org/cdi/api/latest/
•   JBoss Developer Studio - http://devstudio.jboss.com
•   JBoss Tools - http://jboss.org/tools

Contenu connexe

En vedette

Recommendation - Lais Lima
Recommendation - Lais LimaRecommendation - Lais Lima
Recommendation - Lais LimaLais Lima
 
Saml single sign on magento extension sixto martin
Saml single sign on magento extension   sixto martinSaml single sign on magento extension   sixto martin
Saml single sign on magento extension sixto martinNETBASE CMSMART
 
Medicina natural
Medicina naturalMedicina natural
Medicina naturalAC21iune
 
Tycho - good, bad or ugly ?
Tycho - good, bad or ugly ?Tycho - good, bad or ugly ?
Tycho - good, bad or ugly ?Max Andersen
 
Problem çözme teknikleri / Yönetim ve Liderlik Micro MBA Eğitimi / Istanbul B...
Problem çözme teknikleri / Yönetim ve Liderlik Micro MBA Eğitimi / Istanbul B...Problem çözme teknikleri / Yönetim ve Liderlik Micro MBA Eğitimi / Istanbul B...
Problem çözme teknikleri / Yönetim ve Liderlik Micro MBA Eğitimi / Istanbul B...Istanbul_Business_School
 

En vedette (13)

Recommendation - Lais Lima
Recommendation - Lais LimaRecommendation - Lais Lima
Recommendation - Lais Lima
 
Saml single sign on magento extension sixto martin
Saml single sign on magento extension   sixto martinSaml single sign on magento extension   sixto martin
Saml single sign on magento extension sixto martin
 
Mandala presupuesto
Mandala presupuestoMandala presupuesto
Mandala presupuesto
 
B2bwebscoring marancon
B2bwebscoring maranconB2bwebscoring marancon
B2bwebscoring marancon
 
Contabilidad general
Contabilidad generalContabilidad general
Contabilidad general
 
Pedram Resume
Pedram ResumePedram Resume
Pedram Resume
 
Branding principle130118
Branding principle130118Branding principle130118
Branding principle130118
 
Presentation_NEW.PPTX
Presentation_NEW.PPTXPresentation_NEW.PPTX
Presentation_NEW.PPTX
 
Medicina natural
Medicina naturalMedicina natural
Medicina natural
 
Guia abnt site
Guia abnt siteGuia abnt site
Guia abnt site
 
Tycho - good, bad or ugly ?
Tycho - good, bad or ugly ?Tycho - good, bad or ugly ?
Tycho - good, bad or ugly ?
 
Problem çözme teknikleri / Yönetim ve Liderlik Micro MBA Eğitimi / Istanbul B...
Problem çözme teknikleri / Yönetim ve Liderlik Micro MBA Eğitimi / Istanbul B...Problem çözme teknikleri / Yönetim ve Liderlik Micro MBA Eğitimi / Istanbul B...
Problem çözme teknikleri / Yönetim ve Liderlik Micro MBA Eğitimi / Istanbul B...
 
Influencer Marketing
Influencer MarketingInfluencer Marketing
Influencer Marketing
 

Plus de Max Andersen

Quarkus Denmark 2019
Quarkus Denmark 2019Quarkus Denmark 2019
Quarkus Denmark 2019Max Andersen
 
Case study: JBoss Developer Studio, an IDE for Web, Mobile and Cloud applicat...
Case study: JBoss Developer Studio, an IDE for Web, Mobile and Cloud applicat...Case study: JBoss Developer Studio, an IDE for Web, Mobile and Cloud applicat...
Case study: JBoss Developer Studio, an IDE for Web, Mobile and Cloud applicat...Max Andersen
 
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7Max Andersen
 
Enterprise Maven Repository BOF
Enterprise Maven Repository BOFEnterprise Maven Repository BOF
Enterprise Maven Repository BOFMax Andersen
 
Google analytics for Eclipse Plugins
Google analytics for Eclipse PluginsGoogle analytics for Eclipse Plugins
Google analytics for Eclipse PluginsMax Andersen
 
JBoss Enterprise Maven Repository
JBoss Enterprise Maven RepositoryJBoss Enterprise Maven Repository
JBoss Enterprise Maven RepositoryMax Andersen
 
Making Examples Accessible
Making Examples AccessibleMaking Examples Accessible
Making Examples AccessibleMax Andersen
 
OpenShift Express Intro
OpenShift Express IntroOpenShift Express Intro
OpenShift Express IntroMax Andersen
 
JBoss AS 7 from a user perspective
JBoss AS 7 from a user perspectiveJBoss AS 7 from a user perspective
JBoss AS 7 from a user perspectiveMax Andersen
 
How to be effective with JBoss Developer Studio
How to be effective with JBoss Developer StudioHow to be effective with JBoss Developer Studio
How to be effective with JBoss Developer StudioMax Andersen
 
How To Make A Framework Plugin That Does Not Suck
How To Make A Framework Plugin That Does Not SuckHow To Make A Framework Plugin That Does Not Suck
How To Make A Framework Plugin That Does Not SuckMax Andersen
 

Plus de Max Andersen (11)

Quarkus Denmark 2019
Quarkus Denmark 2019Quarkus Denmark 2019
Quarkus Denmark 2019
 
Case study: JBoss Developer Studio, an IDE for Web, Mobile and Cloud applicat...
Case study: JBoss Developer Studio, an IDE for Web, Mobile and Cloud applicat...Case study: JBoss Developer Studio, an IDE for Web, Mobile and Cloud applicat...
Case study: JBoss Developer Studio, an IDE for Web, Mobile and Cloud applicat...
 
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
Red Hat and Oracle: Delivering on the Promise of Interoperability in Java EE 7
 
Enterprise Maven Repository BOF
Enterprise Maven Repository BOFEnterprise Maven Repository BOF
Enterprise Maven Repository BOF
 
Google analytics for Eclipse Plugins
Google analytics for Eclipse PluginsGoogle analytics for Eclipse Plugins
Google analytics for Eclipse Plugins
 
JBoss Enterprise Maven Repository
JBoss Enterprise Maven RepositoryJBoss Enterprise Maven Repository
JBoss Enterprise Maven Repository
 
Making Examples Accessible
Making Examples AccessibleMaking Examples Accessible
Making Examples Accessible
 
OpenShift Express Intro
OpenShift Express IntroOpenShift Express Intro
OpenShift Express Intro
 
JBoss AS 7 from a user perspective
JBoss AS 7 from a user perspectiveJBoss AS 7 from a user perspective
JBoss AS 7 from a user perspective
 
How to be effective with JBoss Developer Studio
How to be effective with JBoss Developer StudioHow to be effective with JBoss Developer Studio
How to be effective with JBoss Developer Studio
 
How To Make A Framework Plugin That Does Not Suck
How To Make A Framework Plugin That Does Not SuckHow To Make A Framework Plugin That Does Not Suck
How To Make A Framework Plugin That Does Not Suck
 

Dernier

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 FMESafe Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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...apidays
 
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...Jeffrey Haguewood
 
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 REVIEWERMadyBayot
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
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 AmsterdamUiPathCommunity
 
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 FMESafe Software
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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 ...apidays
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
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.pdfsudhanshuwaghmare1
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
"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 ...Zilliz
 
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...apidays
 

Dernier (20)

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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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...
 
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
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
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
 
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
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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 ...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
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
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
"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 ...
 
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...
 

See Context & Dependency Injection from Java EE 6 in Action

  • 1.
  • 2. Context & Dependency Injection from Java EE 6 in Action Max Rydahl Andersen Red Hat http://about.me/maxandersen 14th April Miracle Open World 2011
  • 3. About Me • Max Rydahl Andersen • Lead of JBoss Tools & Developer Studio • Committer on Hibernate Core, Seam & Weld • Co-host of JBoss Community Asylum Podcast • @maxandersen on Twitter • http://about.me/maxandersen
  • 4. Today’s goal is to answer ..
  • 5. Today’s goal is to answer .. Is JEE 6 awesome ?
  • 6. Agenda • What is new in Java EE 6 ? • Quick Intro to CDI • Deep-dive Example • Solving real problems with EE 6
  • 7. What is new in Java EE 6 ?
  • 8. What is new in Java EE 6 ?
  • 9. What is new in Java EE 6 ? • Forget everything bad you have seen or heard about Java EE, because... • ...it is highly simplified • ...it’s actually usable now • ...it Just Works!
  • 10. Java EE 6: Goals •Extensibility •Allow more components to be standalone (EJB 3.1) •Profiles •Subsets of “full” EE platform •Web Profile •Pruning •CMP, JAX-RPC, JAXR, JSR-88 are “pruned” in EE6 •Technology Improvements 8 Pete Muir
  • 11. Java EE 6: Newcomers •Managed Beans (part of JSR-316) •Contexts and Dependency Injection - JSR-299 •Bean Validation - JSR-303 •JAX-RS (RESTful Web Services) - JSR-311 9 Pete Muir
  • 12. Java EE 6: Notable Updates •Servlet 3.0 •JSF 2 •Easier configuration •Ajax •JPA 2.0 •Easy component creation •Type-safe Criteria API •Bookmarkable URLs •Extra mappings •Templating •EJB 3.1 10 Pete Muir
  • 13. Web Profile •Persistence •Presentation •JPA 2.0 •JSF 2.0 •JTA •Servlet 3.0 •Component model •EJB 3.1 Lite •Bean Validation •CDI (JSR-299) 11 Pete Muir
  • 15. What is CDI ? • “...unify the JSF managed bean component model with the EJB component model, resulting in a significantly simplified programming model for web-based applications.” - JSR-299/Gavin King • “CDI simplifies and sanitizes the API for DI and AOP like JPA did for ORM” - CDI Tutorial/Rick Hightower
  • 16. CDI Acronyms • The Spec - Context & Dependency Injection for JEE (CDI) • The Reference Implementation - Weld • Other implementations - CanDI (Resin), Open WebBeans (Apache)
  • 17. The Simplest CDI Bean public class Welcome { public String buildPhrase(String city) { return "Hello from " + city + "!"; } }
  • 18. The Simplest Session Bean @Stateless public class Welcome { public String buildPhrase(String city) { return "Hello from " + city + "!"; } }
  • 20. Simplest CDI Packaging Can just be empty!
  • 21. Dependency Injection public class Greeter { Welcome w; public void welcome() { System.out.println(w.buildPhrase("Billund")); } }
  • 22. Dependency Injection public class Greeter { @Inject Welcome w; public void welcome() { System.out.println(w.buildPhrase("Billund")); } }
  • 23. Another Implementation public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate( "Welcome to " + city + "!"); } }
  • 24. Quiz: What gets Injected ? public class Greeter { @Inject Welcome w; // Welcome or TranslatingWelcome ? public void welcome() { System.out.println(w.buildPhrase("Billund")); } }
  • 25. Qualifiers to the rescue @Qualifier @Target({ TYPE, METHOD, PARAMETER, FIELD }) @Retention(RUNTIME) @Documented public @interface Translating { }
  • 26. Qualifiers to the rescue @Translating public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate("Welcome to " + city + "!"); } }
  • 27. Qualifiers to the rescue @Translating public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate("Welcome to " + city + "!"); } }
  • 28. Qualifiers to the rescue @Translating public class TranslatingWelcome extends Welcome { @Inject GoogleTranslator translator; public String buildPhrase(String city) { return translator.translate("Welcome to " + city + "!"); } public class Greeter { } @Inject @Translating Welcome w; // No ambigiuty! public void welcome() { System.out.println(w.buildPhrase("Billund")); } }
  • 29. @Produces public class WelcomeProducer { @Produces @Translating Welcome createWelcome() { return new TranslatingWelcome(); } }
  • 30. Scopes • JEE 6 provides a set of Scopes • @Dependent, @ApplicationScoped, @RequestScoped, @SessionScoped, @ConversationScoped, <put your own here> • Each have a context which are managed by the container (you don’t have to do explicit cleanup)
  • 31. More CDI • Event/Observers • Stereo Types • Alternatives • API for Framework Implementors
  • 32. Deep-dive Example • PasteCode - part of the Weld Examples • Uses just Servlet, CDI, JSF & EJB’s • JEE 6 Web Profile
  • 33. Challenges • Persistence • Validation of data from client to database • Configuration of Servlet’s, EJB’s etc. • Access to Beans from UI-Layer (EJB->JSF) • Dependency Injection for decoupling concerns • Setup things at Application Startup • Cross-cutting custom business concerns (example Flood Control) • Sending and receiving events • Batch job’s • ...and more
  • 34. CDI Bean In Action public class PasteWindow { ... private CodeFragmentManager codeFragmentManager;t public CodeFragment getCodeFragment() { return codeFragment; } …
  • 35. CDI Bean In Action @Named public class PasteWindow { ... private CodeFragmentManager codeFragmentManager;t public CodeFragment getCodeFragment() { return codeFragment; } …
  • 36. CDI Bean In Action @Named @RequestScoped public class PasteWindow { ... private CodeFragmentManager codeFragmentManager;t public CodeFragment getCodeFragment() { return codeFragment; } …
  • 37. CDI Bean In Action @Named @RequestScoped public class PasteWindow { ... @Inject private CodeFragmentManager codeFragmentManager;t public CodeFragment getCodeFragment() { return codeFragment; } …
  • 38. Persistence/Validation @Entity public class CodeFragment { @Id @GeneratedValue(strategy = AUTO) @Column(name = "id") private int id; @Lob @Size(min=1, message="Must enter some text!") private String text; … }
  • 39. Application Startup @Startup @Singleton public class PopulateDatabase { @PersistenceContext private EntityManager entityManager; @PostConstruct public void startup() { … } }
  • 40. Sending and receiving events @Inject private Event<CodeFragment> event; ... event.fire(code); public void addEntry(@Observes CodeFragment codeFragment) { this.log.add(codeFragment); }
  • 41. Cross-Cutting Business @Decorator w/Decoratorimplements public abstract class FloodingDecorator CodeFragmentManager, Serializable { @Inject @Delegate private CodeFragmentManage codeFragmentManager; public String addCodeFragment(CodeFragment code, boolean privateFragment) { ... return codeFragmentManager.addCodeFragment(code, privateFragment);
  • 42. Summary • JSR-299 provides a set of services for Java EE • Bridges JSF and EJB • Offers loose coupling with strong typing • Extensive SPI for third-party integration with Java EE • Weld: JSR-299 Reference Implementation • Seam 3: Portable extensions for Java EE
  • 44. Q &A ? JEE 6 is awesome! Rate this talk: http://bit.ly/cdiaction
  • 45. Q &A ? • Weld - http://seamframework.org/Weld • Seam 3 project - http://seamframework.org/Seam3 • Weld Maven archetypes for CDI and Java EE - http://tinyurl.com/ goweld • Weld reference guide - http://tinyurl.com/weld-reference-101 • CDI JavaDoc - http://docs.jboss.org/cdi/api/latest/ • JBoss Developer Studio - http://devstudio.jboss.com • JBoss Tools - http://jboss.org/tools

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. * Emphsize the web profile - lightweight, aimed at developing &amp;#x201C;web&amp;#x201D; apps\n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n