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

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
 
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...Martijn de Jong
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
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
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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
 
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
 
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
 
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 Takeoffsammart93
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Dernier (20)

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
 
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...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
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
 
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
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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...
 
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...
 
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
 
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
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

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