SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Destaque

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
 

Destaque (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
 

Mais 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
 

Mais 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
 

Último

[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.pdfhans926745
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
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 WorkerThousandEyes
 
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...apidays
 
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...Neo4j
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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 2024Rafal Los
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
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 organizationRadu Cotescu
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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...Drew Madelung
 
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 MenDelhi Call girls
 
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 Servicegiselly40
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Último (20)

[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
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
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...
 
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...
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
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
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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...
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

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

Notas do Editor

  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