SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Reverse Engineering 안드로이드 학습
Reverse Engineering 안드로이드 학습Reverse Engineering 안드로이드 학습
Reverse Engineering 안드로이드 학습Sungju Jin
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which workDmitry Zaytsev
 
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 HTML5Arun Gupta
 
JavaEE with Vaadin - Workshop
JavaEE with Vaadin - WorkshopJavaEE with Vaadin - Workshop
JavaEE with Vaadin - WorkshopPeter Lehto
 
OSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersOSGi Training for Carbon Developers
OSGi Training for Carbon DevelopersAruna Karunarathna
 
Deep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle LayerDeep dive into OSGi Lifecycle Layer
Deep dive into OSGi Lifecycle LayerAruna Karunarathna
 
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 2Matt Raible
 
12 global fetching strategies
12 global fetching strategies12 global fetching strategies
12 global fetching strategiesthirumuru2012
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin componentsPeter Lehto
 
ZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsZooKeeper Recipes and Solutions
ZooKeeper Recipes and SolutionsJeff Smith
 
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 JUGArun Gupta
 
YAML is the new Eval
YAML is the new EvalYAML is the new Eval
YAML is the new Evalarnebrasseur
 
"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил Анохин"Android Data Binding в массы" Михаил Анохин
"Android Data Binding в массы" Михаил АнохинFwdays
 
Parsley & Flex
Parsley & FlexParsley & Flex
Parsley & Flexprideconan
 
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 VRaptorCaelum
 
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 2018Luciano Mammino
 

Was ist angesagt? (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
 

Andere mochten auch

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 TreaderSaltmarch Media
 
Caring about Code Quality
Caring about Code QualityCaring about Code Quality
Caring about Code QualitySaltmarch Media
 
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 DevelopersSaltmarch Media
 
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 AzureSaltmarch Media
 
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 TimeSaltmarch Media
 
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?Saltmarch Media
 
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.0Saltmarch Media
 
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 paisajeRoberto Marin
 
Integrated Services for Web Applications
Integrated Services for Web ApplicationsIntegrated Services for Web Applications
Integrated Services for Web ApplicationsSaltmarch Media
 
Building Facebook Applications on Windows Azure
Building Facebook Applications on Windows AzureBuilding Facebook Applications on Windows Azure
Building Facebook Applications on Windows AzureSaltmarch Media
 
Learning Open Source Business Intelligence
Learning Open Source Business IntelligenceLearning Open Source Business Intelligence
Learning Open Source Business IntelligenceSaltmarch Media
 
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 DevelopmentSaltmarch Media
 
“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 PracticesSaltmarch Media
 
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...Axel Valiente Bautista
 
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 6Saltmarch Media
 

Andere mochten auch (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
 

Ähnlich wie 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 & JSFJiayun Zhou
 
Spring training
Spring trainingSpring training
Spring trainingTechFerry
 
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 serializationPVS-Studio
 
Spring Performance Gains
Spring Performance GainsSpring Performance Gains
Spring Performance GainsVMware Tanzu
 
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)Markus Eisele
 
jRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServicejRecruiter - The AJUG Job Posting Service
jRecruiter - The AJUG Job Posting ServiceGunnar Hillert
 
OpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConOpenWebBeans and DeltaSpike at ApacheCon
OpenWebBeans and DeltaSpike at ApacheConos890
 
Gnizr Architecture (for developers)
Gnizr Architecture (for developers)Gnizr Architecture (for developers)
Gnizr Architecture (for developers)hchen1
 
Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Context and Dependency Injection 2.0
Context and Dependency Injection 2.0Brian S. Paskin
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's NewTed Pennings
 
CloudStack Meetup Santa Clara
CloudStack Meetup Santa Clara CloudStack Meetup Santa Clara
CloudStack Meetup Santa Clara NetApp
 
DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)DataFX 8 (JavaOne 2014)
DataFX 8 (JavaOne 2014)Hendrik Ebbers
 
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-WAREFermin Galan
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 

Kürzlich hochgeladen (20)

Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 

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