SlideShare une entreprise Scribd logo
1  sur  31
Context &
Dependency Injection
A Cocktail of Guice and Seam, the
missing ingredients for Java EE 6




           Werner Keil
           21/04/2011
Without Dependency Injection
Explicit Constructor
class Stopwatch {
     final TimeSource timeSource;
     Stopwatch () {
       timeSource = new AtomicClock(...);
     }
     void start() { ... }
     long stop() { ... }
}



www.catmedia.us                             2
Without Dependency Injection
Using a Factory
class Stopwatch {
     final TimeSource timeSource;
     Stopwatch () {
         timeSource =
    DefaultTimeSource.getInstance();
       }
       void start() { ... }
       long stop() { ... }
}                     Somewhat like in java.util.Calendar
www.catmedia.us                                         3
Without Dependency Injection
Mock Data
void testStopwatch() {
   TimeSource original = DTS.getInstance();
     DefaultTimeSource.setInstance(new
  MockTimeSource());
     try {
     Stopwatch sw = new Stopwatch();
       ...
     } finally {
      DTS.setInstance(original);
     }
}
www.catmedia.us                               4
With Dependency Injection
@Inject
class Stopwatch {
      final TimeSource timeSource;
      @Inject Stopwatch(TimeSource timeSource)
  {
        this.timeSource = TimeSource;
      }
      void start() { ... }
      long stop() { ... }
    }


www.catmedia.us                             5
JSR-330
Definition
 @Inject
      Identifies injectable constructors, methods, and fields .
       This works for both static and non-static elements.
 @Qualifier
      Identifies qualifier annotations to declare binding types of
       your API
 @Named
      A name (string) based qualifier
      Others may be declared application - or domain-specific
www.catmedia.us                                                       6
JSR-330
Implementation
 @Provider
      Provides instances of an (injectable) type. Allows
                 Retrieving multiple instances.
                 Lazy or optional retrieval of an instance.
                 Breaking circular dependencies.
                 Abstracting scope
 @Singleton
      Identifies a type that the injector only instantiates once.
      See the well-known Design Pattern

www.catmedia.us                                                      7
DEMO




www.catmedia.us          8
JSR-330
Configuration
1. Minimal but usable API: A small API surface seems
   more important than making it as convenient as
   possible for clients. There are only two methods in
   the proposed API that could be considered
   convenience, added because they seemed to pull
   their weight
      InjectionConfigurer.inject and InjectionSpec.inject(Object)
2. Builder-style API: so-called "fluent APIs“
     •      Open to other styles.
www.catmedia.us                                                      9
JSR-330
Configuration (2)
3. Abstract classes instead of interfaces: 2 main types
      (InjectionConfigurer and InjectionSpec) are abstract classes
       instead of interfaces.
      This allows new methods to be added later in a binary-
       compatible way.
4. Separate configuration API
     •      The API does not specify how an instance of
            InjectionConfigurer is obtained.
     •      Otherwise we have to standardize the injector API itself,
            something outside of the stated scope of JSR-330.
www.catmedia.us                                                         10
JSR-330
Configuration (3)
5. Names are different from Guice's configuration API:
   This is mostly
 to keep this separate from existing configuration APIs,
   but also so
 that new concepts (like "Binding") don't have to be
   defined.



www.catmedia.us                                        11
More about JSR-330, see
      http://code.google.com/p/atinject
                        or
http://jcp.org/en/jsr/summary?id=330



www.catmedia.us                           12
Formerly known as WebBeans…




www.catmedia.us                   13
JSR-299
Services
 The lifecycle and interactions of stateful components
  bound to well-defined lifecycle contexts, where the
  set of contexts is extensible
 A sophisticated, type safe dependency injection
  mechanism, including a facility for choosing between
  various components that implement the same Java
  interface at deployment time
 An event notification model

www.catmedia.us                                       14
JSR-299
Services (2)
 Integration with the Unified Expression Language (EL),
  allowing any component to be used directly within a
  JSF or JSP page
 The ability to decorate injected components
 A web conversation context in addition to the three
  standard web contexts defined by the Java Servlets
  specification
 An SPI allowing portable extensions to integrate
  cleanly with the Java EE environment
www.catmedia.us                                       15
• Sophisticated,
• Type Safe,
• Dependency
  Injection,…




www.catmedia.us    16
IN MEMORIAM
Pietro Ferrero Jr.




                  11 September 1963 – 18 April 2011

www.catmedia.us                                       17
JSR-299
Bean Attributes
   A (nonempty) set of bean types
   A (nonempty) set of bindings
   A scope
   A deployment type
   Optionally, a bean EL name
   A set of interceptor bindings
   A bean implementation

www.catmedia.us                      18
JSR-299
Context
• A custom implementation of Context may be
  associated with a scope type by calling
  BeanManager.addContext().

public void addContext(Context context);




www.catmedia.us                               19
JSR-299
Context (2)
• BeanManager.getContext() retrieves an active context
  object associated with the a given scope:

public Context getContext(Class<? extends
  Annotation> scopeType);


→ Context used in a broader meaning than some other
 parts of Java (Enterprise)

www.catmedia.us                                     20
JSR-299
Restricted Instantiation
@SessionScoped
public class PaymentStrategyProducer {
    private PaymentStrategyType
    paymentStrategyType;

    public void setPaymentStrategyType(
      PaymentStrategyType type) {
       paymentStrategyType = type;
    }
www.catmedia.us                           21
JSR-299
Restricted Instantiation (2)
@Produces PaymentStrategy
  getPaymentStrategy(@CreditCard
  PaymentStrategy creditCard,
@Cheque PaymentStrategy cheque,
@Online PaymentStrategy online) {
  switch (paymentStrategyType) {
       case CREDIT_CARD: return creditCard;
       case CHEQUE: return cheque;
[…]

www.catmedia.us                           22
JSR-299
Restricted Instantiation (3)
[…]
         case ONLINE: return online;
         default: throw new
    IllegalStateException();
       }
    }
}




www.catmedia.us                        23
JSR-299
Event Observer
• Then the following observer method will always be
  notified of the event:
• public void afterLogin(@Observes
  LoggedInEvent event) { ... }


• Whereas this observer method may or may not be notified,
  depending upon the value of user.getRole():
• public void afterAdminLogin(@Observes
  @Role("admin") LoggedInEvent event) { ... }

www.catmedia.us                                        24
JSR-299
Event Binding
• As elsewhere, binding types may have annotation
  members:
@BindingType
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Role {
  String value();
}
www.catmedia.us                                     25
JSR-299
Event Binding (2)
 Actually @Role could extend @Named from JSR-330
 JSRs here potentially not consequently streamlined…?




www.catmedia.us                                     26
JSR-299
Portable Extensions
public interface Bean<T>
extends Contextual<T> {
  public Set<Type> getTypes();
  public Set<Annotation>
  getBindings();
  public Class<? extends Annotation>
                      getScopeType();


www.catmedia.us                         27
JSR-299
Portable Extensions (2)
    public Class<? extends Annotation>

     getDeploymentType();
  public String getName();
  public Class<?> getBeanClass();
  public boolean isNullable();
public Set<InjectionPoint>
  getInjectionPoints();
}
www.catmedia.us                          28
DEMO




www.catmedia.us          31
More about JSR-299, see
       http://www.seamframework.org/
                            JCP
 http://jcp.org/en/jsr/summary?id=299
                   or
http://www.developermarch.com/devel
  opersummit/sessions.html#session66
                       (cancelled ;-/)
www.catmedia.us               32
Further Reading
     • Java.net
       http://www.java.net/
     • Java™ EE Patterns and Best Practices
       http://kenai.com/projects/javaee-patterns /




www.catmedia.us                                  33

Contenu connexe

Tendances

12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategies
thirumuru2012
 
YAML is the new Eval
YAML is the new EvalYAML is the new Eval
YAML is the new Eval
arnebrasseur
 
Parsley & Flex
Parsley & FlexParsley & Flex
Parsley & Flex
prideconan
 

Tendances (19)

Reverse Engineering 안드로이드 학습
Reverse Engineering 안드로이드 학습Reverse Engineering 안드로이드 학습
Reverse Engineering 안드로이드 학습
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which work
 
The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5The Java EE 7 Platform: Productivity++ & Embracing HTML5
The Java EE 7 Platform: Productivity++ & Embracing HTML5
 
JavaEE with Vaadin - Workshop
JavaEE with Vaadin - WorkshopJavaEE with Vaadin - Workshop
JavaEE with Vaadin - Workshop
 
Sql full tutorial
Sql full tutorialSql full tutorial
Sql full tutorial
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
OSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersOSGi Training for Carbon Developers
OSGi Training for Carbon Developers
 
Deep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle LayerDeep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle Layer
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategies
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin components
 
14 hql
14 hql14 hql
14 hql
 
ZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsZooKeeper Recipes and Solutions
ZooKeeper Recipes and Solutions
 
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUGThe Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
The Java EE 7 Platform: Productivity &amp; HTML5 at San Francisco JUG
 
YAML is the new Eval
YAML is the new EvalYAML is the new Eval
YAML is the new Eval
 
"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин
 
Parsley & Flex
Parsley & FlexParsley & Flex
Parsley & Flex
 
CDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptorCDI e as ideias pro futuro do VRaptor
CDI e as ideias pro futuro do VRaptor
 
Unbundling the JavaScript module bundler - DublinJS July 2018
Unbundling the JavaScript module bundler - DublinJS July 2018Unbundling the JavaScript module bundler - DublinJS July 2018
Unbundling the JavaScript module bundler - DublinJS July 2018
 

En vedette

Fuerzas internas y externas que forman el paisaje
Fuerzas internas y externas que forman el paisajeFuerzas internas y externas que forman el paisaje
Fuerzas internas y externas que forman el paisaje
Roberto Marin
 

En vedette (16)

Java EE 7: the Voyage of the Cloud Treader
Java EE 7: the Voyage of the Cloud TreaderJava EE 7: the Voyage of the Cloud Treader
Java EE 7: the Voyage of the Cloud Treader
 
Caring about Code Quality
Caring about Code QualityCaring about Code Quality
Caring about Code Quality
 
Introduction to WCF RIA Services for Silverlight 4 Developers
Introduction to WCF RIA Services for Silverlight 4 DevelopersIntroduction to WCF RIA Services for Silverlight 4 Developers
Introduction to WCF RIA Services for Silverlight 4 Developers
 
Concocting an MVC, Data Services and Entity Framework solution for Azure
Concocting an MVC, Data Services and Entity Framework solution for AzureConcocting an MVC, Data Services and Entity Framework solution for Azure
Concocting an MVC, Data Services and Entity Framework solution for Azure
 
Gaelyk - Web Apps In Practically No Time
Gaelyk - Web Apps In Practically No TimeGaelyk - Web Apps In Practically No Time
Gaelyk - Web Apps In Practically No Time
 
Is NoSQL The Future of Data Storage?
Is NoSQL The Future of Data Storage?Is NoSQL The Future of Data Storage?
Is NoSQL The Future of Data Storage?
 
Building RESTful Services with WCF 4.0
Building RESTful Services with WCF 4.0Building RESTful Services with WCF 4.0
Building RESTful Services with WCF 4.0
 
Fuerzas internas y externas que forman el paisaje
Fuerzas internas y externas que forman el paisajeFuerzas internas y externas que forman el paisaje
Fuerzas internas y externas que forman el paisaje
 
Integrated Services for Web Applications
Integrated Services for Web ApplicationsIntegrated Services for Web Applications
Integrated Services for Web Applications
 
Building Facebook Applications on Windows Azure
Building Facebook Applications on Windows AzureBuilding Facebook Applications on Windows Azure
Building Facebook Applications on Windows Azure
 
Learning Open Source Business Intelligence
Learning Open Source Business IntelligenceLearning Open Source Business Intelligence
Learning Open Source Business Intelligence
 
CDI and Seam 3: an Exciting New Landscape for Java EE Development
CDI and Seam 3: an Exciting New Landscape for Java EE DevelopmentCDI and Seam 3: an Exciting New Landscape for Java EE Development
CDI and Seam 3: an Exciting New Landscape for Java EE Development
 
“What did I do?” - T-SQL Worst Practices
“What did I do?” - T-SQL Worst Practices“What did I do?” - T-SQL Worst Practices
“What did I do?” - T-SQL Worst Practices
 
Diseño de programas de mercadotecnia directa promocion de eventos organizacio...
Diseño de programas de mercadotecnia directa promocion de eventos organizacio...Diseño de programas de mercadotecnia directa promocion de eventos organizacio...
Diseño de programas de mercadotecnia directa promocion de eventos organizacio...
 
JBoss at Work: Using JBoss AS 6
JBoss at Work: Using JBoss AS 6JBoss at Work: Using JBoss AS 6
JBoss at Work: Using JBoss AS 6
 
Agile Estimation
Agile EstimationAgile Estimation
Agile Estimation
 

Similaire à A Cocktail of Guice and Seam, the missing ingredients for Java EE 6

Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
Ted Pennings
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
Fermin Galan
 

Similaire à A Cocktail of Guice and Seam, the missing ingredients for Java EE 6 (20)

Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
CDI @javaonehyderabad
CDI @javaonehyderabadCDI @javaonehyderabad
CDI @javaonehyderabad
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
 
Spring training
Spring trainingSpring training
Spring training
 
How to not shoot yourself in the foot when working with serialization
How to not shoot yourself in the foot when working with serializationHow to not shoot yourself in the foot when working with serialization
How to not shoot yourself in the foot when working with serialization
 
Java 7: Quo vadis?
Java 7: Quo vadis?Java 7: Quo vadis?
Java 7: Quo vadis?
 
Spring Performance Gains
Spring Performance GainsSpring Performance Gains
Spring Performance Gains
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
 
jRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServicejRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting Service
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheCon
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)
 
Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Context and Dependency Injection 2.0
Context and Dependency Injection 2.0
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
CloudStack Meetup Santa Clara
CloudStack Meetup Santa Clara CloudStack Meetup Santa Clara
CloudStack Meetup Santa Clara
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)
 
Spock
SpockSpock
Spock
 
Developing your first application using FI-WARE
Developing your first application using FI-WAREDeveloping your first application using FI-WARE
Developing your first application using FI-WARE
 
Introduction to Struts 2
Introduction to Struts 2Introduction to Struts 2
Introduction to Struts 2
 
Java EE 6
Java EE 6Java EE 6
Java EE 6
 

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 FME
Safe Software
 

Dernier (20)

AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
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
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
"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 ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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
 
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...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

A Cocktail of Guice and Seam, the missing ingredients for Java EE 6

  • 1. Context & Dependency Injection A Cocktail of Guice and Seam, the missing ingredients for Java EE 6 Werner Keil 21/04/2011
  • 2. Without Dependency Injection Explicit Constructor class Stopwatch { final TimeSource timeSource; Stopwatch () { timeSource = new AtomicClock(...); } void start() { ... } long stop() { ... } } www.catmedia.us 2
  • 3. Without Dependency Injection Using a Factory class Stopwatch { final TimeSource timeSource; Stopwatch () { timeSource = DefaultTimeSource.getInstance(); } void start() { ... } long stop() { ... } } Somewhat like in java.util.Calendar www.catmedia.us 3
  • 4. Without Dependency Injection Mock Data void testStopwatch() { TimeSource original = DTS.getInstance(); DefaultTimeSource.setInstance(new MockTimeSource()); try { Stopwatch sw = new Stopwatch(); ... } finally { DTS.setInstance(original); } } www.catmedia.us 4
  • 5. With Dependency Injection @Inject class Stopwatch { final TimeSource timeSource; @Inject Stopwatch(TimeSource timeSource) { this.timeSource = TimeSource; } void start() { ... } long stop() { ... } } www.catmedia.us 5
  • 6. JSR-330 Definition  @Inject  Identifies injectable constructors, methods, and fields . This works for both static and non-static elements.  @Qualifier  Identifies qualifier annotations to declare binding types of your API  @Named  A name (string) based qualifier  Others may be declared application - or domain-specific www.catmedia.us 6
  • 7. JSR-330 Implementation  @Provider  Provides instances of an (injectable) type. Allows  Retrieving multiple instances.  Lazy or optional retrieval of an instance.  Breaking circular dependencies.  Abstracting scope  @Singleton  Identifies a type that the injector only instantiates once.  See the well-known Design Pattern www.catmedia.us 7
  • 9. JSR-330 Configuration 1. Minimal but usable API: A small API surface seems more important than making it as convenient as possible for clients. There are only two methods in the proposed API that could be considered convenience, added because they seemed to pull their weight  InjectionConfigurer.inject and InjectionSpec.inject(Object) 2. Builder-style API: so-called "fluent APIs“ • Open to other styles. www.catmedia.us 9
  • 10. JSR-330 Configuration (2) 3. Abstract classes instead of interfaces: 2 main types  (InjectionConfigurer and InjectionSpec) are abstract classes instead of interfaces.  This allows new methods to be added later in a binary- compatible way. 4. Separate configuration API • The API does not specify how an instance of InjectionConfigurer is obtained. • Otherwise we have to standardize the injector API itself, something outside of the stated scope of JSR-330. www.catmedia.us 10
  • 11. JSR-330 Configuration (3) 5. Names are different from Guice's configuration API: This is mostly  to keep this separate from existing configuration APIs, but also so  that new concepts (like "Binding") don't have to be defined. www.catmedia.us 11
  • 12. More about JSR-330, see http://code.google.com/p/atinject or http://jcp.org/en/jsr/summary?id=330 www.catmedia.us 12
  • 13. Formerly known as WebBeans… www.catmedia.us 13
  • 14. JSR-299 Services  The lifecycle and interactions of stateful components bound to well-defined lifecycle contexts, where the set of contexts is extensible  A sophisticated, type safe dependency injection mechanism, including a facility for choosing between various components that implement the same Java interface at deployment time  An event notification model www.catmedia.us 14
  • 15. JSR-299 Services (2)  Integration with the Unified Expression Language (EL), allowing any component to be used directly within a JSF or JSP page  The ability to decorate injected components  A web conversation context in addition to the three standard web contexts defined by the Java Servlets specification  An SPI allowing portable extensions to integrate cleanly with the Java EE environment www.catmedia.us 15
  • 16. • Sophisticated, • Type Safe, • Dependency Injection,… www.catmedia.us 16
  • 17. IN MEMORIAM Pietro Ferrero Jr. 11 September 1963 – 18 April 2011 www.catmedia.us 17
  • 18. JSR-299 Bean Attributes  A (nonempty) set of bean types  A (nonempty) set of bindings  A scope  A deployment type  Optionally, a bean EL name  A set of interceptor bindings  A bean implementation www.catmedia.us 18
  • 19. JSR-299 Context • A custom implementation of Context may be associated with a scope type by calling BeanManager.addContext(). public void addContext(Context context); www.catmedia.us 19
  • 20. JSR-299 Context (2) • BeanManager.getContext() retrieves an active context object associated with the a given scope: public Context getContext(Class<? extends Annotation> scopeType); → Context used in a broader meaning than some other parts of Java (Enterprise) www.catmedia.us 20
  • 21. JSR-299 Restricted Instantiation @SessionScoped public class PaymentStrategyProducer { private PaymentStrategyType paymentStrategyType; public void setPaymentStrategyType( PaymentStrategyType type) { paymentStrategyType = type; } www.catmedia.us 21
  • 22. JSR-299 Restricted Instantiation (2) @Produces PaymentStrategy getPaymentStrategy(@CreditCard PaymentStrategy creditCard, @Cheque PaymentStrategy cheque, @Online PaymentStrategy online) { switch (paymentStrategyType) { case CREDIT_CARD: return creditCard; case CHEQUE: return cheque; […] www.catmedia.us 22
  • 23. JSR-299 Restricted Instantiation (3) […] case ONLINE: return online; default: throw new IllegalStateException(); } } } www.catmedia.us 23
  • 24. JSR-299 Event Observer • Then the following observer method will always be notified of the event: • public void afterLogin(@Observes LoggedInEvent event) { ... } • Whereas this observer method may or may not be notified, depending upon the value of user.getRole(): • public void afterAdminLogin(@Observes @Role("admin") LoggedInEvent event) { ... } www.catmedia.us 24
  • 25. JSR-299 Event Binding • As elsewhere, binding types may have annotation members: @BindingType @Target(PARAMETER) @Retention(RUNTIME) public @interface Role { String value(); } www.catmedia.us 25
  • 26. JSR-299 Event Binding (2)  Actually @Role could extend @Named from JSR-330  JSRs here potentially not consequently streamlined…? www.catmedia.us 26
  • 27. JSR-299 Portable Extensions public interface Bean<T> extends Contextual<T> { public Set<Type> getTypes(); public Set<Annotation> getBindings(); public Class<? extends Annotation> getScopeType(); www.catmedia.us 27
  • 28. JSR-299 Portable Extensions (2) public Class<? extends Annotation> getDeploymentType(); public String getName(); public Class<?> getBeanClass(); public boolean isNullable(); public Set<InjectionPoint> getInjectionPoints(); } www.catmedia.us 28
  • 30. More about JSR-299, see http://www.seamframework.org/ JCP http://jcp.org/en/jsr/summary?id=299 or http://www.developermarch.com/devel opersummit/sessions.html#session66 (cancelled ;-/) www.catmedia.us 32
  • 31. Further Reading • Java.net http://www.java.net/ • Java™ EE Patterns and Best Practices http://kenai.com/projects/javaee-patterns / www.catmedia.us 33