Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Â
Using Contexts & Dependency Injection in the Java EE 6 Platform
1. <Insert Picture Here>
Contexts And Dependency Injection In The Java EE 6 Ecosystem
Arun Gupta
Java EE & GlassFish Guy
blogs.sun.com/arungupta, @arungupta
4. The following is intended to outline our general product
direction. It is intended for information purposes only,
and may not be incorporated into any contract. It is not a
commitment to deliver any material, code, or functionality,
and should not be relied upon in making purchasing
decisions.
The development, release, and timing of any features or
functionality described for Oracleâs products remains at the
sole discretion of Oracle.
4
5. How we got here ?
⢠Java EE 5 had resource injection
â @EJB, @PersistenceUnit, @Resource
⢠Motivated by Seam, Guice, and Spring
â More typesafe than Seam
â More stateful and less XML-centric than Spring
â More web and enterprise-capable than Guice
⢠Adapts JSR 330 for Java EE environments
â @Inject, @Qualifier, @ScopeType
5
6. CDI Key Concepts
⢠Type-safe approach to Dependency Injection
⢠Strong typing, Loose coupling
â Events, Interceptors, Decorators
⢠Context & Scope management
⢠Works with Java EE modular and component architecture
â Integration with Unified Expression Language (UEL)
⢠Portable extensions
⢠Bridge EJB (transactional tier) and JSF (presentation tier) in
the platform
6
7. What is a CDI managed bean ?
⢠âBeansâ
â All managed beans by other Java EE specifications
⢠Except JPA
â Meets the following conditions
⢠Non-static inner class
⢠Concrete class or decorated with @Decorator
⢠Constructor with no parameters or a constructor annotated with @Inject
⢠âContextual instancesâ - Instances of âbeansâ that belong to
contexts
7
8. How to configure ?
There is none!
⢠Discovers bean in all modules in which CDI is enabled
⢠âbeans.xmlâ
â WEB-INF of WAR
â META-INF of JAR
â META-INF of directory in the classpath
⢠Can enable groups of bean selectively via a descriptor
8
9. Injection Points
⢠Field, Method, Constructor
⢠0 or more qualifiers
Which one ?
⢠Type (Qualifier)
@Inject @LoggedIn User user
Request What ?
Injection (Type)
9
10. Basic â Sample Code
public interface Greeting {
public String sayHello(String name); Default âdependentâ
scope
}
public class HelloGreeting implements Greeting {
public String sayHello(String name) {
return âHello â + name;
}
}
@Stateless
public class GreetingService {
@Inject Greeting greeting;
public String sayHello(String name) { No String identifiers,
return greeting.sayHello(name); All Java
}
}
10
11. Qualifier
⢠Annotation to uniquely identify a bean to be injected
⢠Built-in qualifiers
â @Named required for usage in EL
â @Default qualifier on all beans marked with/without @Named
â @Any implicit qualifier for all beans (except @New)
â @New
11
12. Qualifier â Sample Code
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface Texan {
}
@Texan
public class HowdyGreeting implements Greeting {
public String sayHello(String name) {
return âHowdy â + name;
}
}
@Stateless
public class GreetingService {
@Inject @Texan Greeting greeting;
public String sayHello(String name) {
return greeting.sayHello(name);
}
}
12
13. Field and Method Injection
public class CheckoutHandler {
@Inject @LoggedIn User user;
@Inject PaymentProcessor processor;
@Inject
void setShoppingCart(@Default Cart cart) {
âŚ
}
}
13
14. Constructor Injection
public class CheckoutHandler {
@Inject
CheckoutHandler(@LoggedIn User user,
PaymentProcessor processor,
Cart cart) {
...
}
}
⢠Only one constructor can have @Inject
⢠Makes the bean immutable
14
15. Multiple Qualifiers and Qualifiers with Arguments
public class CheckoutHandler {
@Inject
CheckoutHandler(@LoggedIn User user,
@Reliable
@PayBy(CREDIT_CARD)
PaymentProcessor processor,
@Default Cart cart) {
...
}
}
15
16. Bean Initialization Sequence
1. Default bean constructor or the one annotated with @Inject
2. Values of all injected fields of the beans
3. All initializer methods of the beans
1.Defined within bean hierarchy
2. Call order not portable within a single bean
4. @PostConstruct method
16
17. Typesafe Resolution
⢠Resolution is performed at system initialization time
⢠@Qualifier, @Alternative
â Unsatisfied dependency
⢠Create a bean which implements the bean type with all qualifiers
⢠Explicitly enable an @Alternative bean using beans.xml
⢠Make sure it is in the classpath
â Ambiguous dependency
⢠Introduce a qualifier
⢠Disable one of the beans using @Alternative
⢠Move one implementation out of classpath
17
18. Client Proxies
⢠Container indirects all injected references through a proxy
object unless it is @Dependent
⢠Proxies may be shared between multiple injection points
@ApplicationScoped @RequestScoped
public class UserService { public class User {
private String message;
@Inject User user; // getter & setter
}
public void doSomething() {
user.setMessage("...");
// some other stuff
user.getMessage();
}
}
18
19. Scopes
⢠Beans can be declared in a scope
â Everywhere: @ApplicationScoped, @RequestScoped
â Web app: @SessionScoped (must be serializable)
â JSF app: @ConversationScoped
⢠Transient and long-running
â Pseudo-scope (default): @Dependent
â Custom scopes via @Scope
⢠Runtime makes sure the right bean is created at the right time
⢠Client do NOT have to be scope-aware
19
20. ConversationScope â Sample Code
⢠Like session-scope â spans multiple requests to the server
⢠Unlike â demarcated explicitly by the application, holds state
with a particular browser tab in a JSF application
public class ShoppingService {
@Inject Conversation conv;
public void startShopping() {
conv.begin();
}
. . .
public void checkOut() {
conv.end();
}
}
20
21. Custom Scopes â Sample Code
@ScopeType
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface ClusterScoped {}
public @interface TransactionScoped {}
public @interface ThreadScoped {}
21
22. @New Qualifier
⢠Allows to obtain a dependent object of a specified class,
independent of declared scope
â Useful with @Produces
@ConversationScoped
public class Calculator { . . . }
public class PaymentCalc {
@Inject Calculator calculator;
@Inject @New Calculator newCalculator;
}
22
23. Producer & Disposer
⢠Producer
â Exposes any non-bean class as a bean, e.g. a JPA entity
â Bridge the gap with Java EE DI
â Perform custom initialization not possible in a constructor
â Define multiple beans, with different scopes or initialization, for the
same implementation class
â Method or field
â Runtime polymorphism
⢠Disposer â cleans up the âproducedâ object
â e.g. explicitly closing JDBC connection
â Defined in the same class as the âproducerâ method
23
24. Producer â Sample Code
@SessionScoped
public class Preferences implements Serializable {
How often the method is called,
private PaymentStrategyType paymentStrategy;
Lifecycle of the objects returned
. . .
Default is @Dependent
@Produces @Preferred @SessionScoped
public PaymentStrategy getPaymentStrategy() {
switch (paymentStrategy) {
case CREDIT_CARD: return new CreditCardPaymentStrategy();
case CHECK: return new CheckPaymentStrategy();
case PAYPAL: return new PayPalPaymentStrategy();
default: return null;
}
}
}
@Inject @Preferred PaymentStrategy paymentStrategy;
24
26. Interceptors
⢠Two interception points on a target class
â Business method
â Lifecycle callback
⢠Cross-cutting concerns: logging, auditing, profiling
⢠Different from EJB 3.0 Interceptors
â Type-safe, Enablement/ordering via beans.xml, ...
⢠Defined using annotations and DD
⢠Class & Method Interceptors
â In the same transaction & security context
â˘
26
27. Interceptors â Business Method (Logging)
@InterceptorBinding @LoggingInterceptorBinding
public class MyManagedBean {
@Retention(RUNTIME) . . .
@Target({METHOD,TYPE}) }
public @interface LoggingInterceptorBinding {
}
@Interceptor
@LoggingInterceptorBinding
public class @LogInterceptor {
@AroundInvoke
public Object log(InvocationContext context) {
System.out.println(context.getMethod().getName());
System.out.println(context.getParameters());
return context.proceed();
}
}
27
28. Why Interceptor Bindings ?
⢠Remove dependency from the interceptor implementation class
⢠Can vary depending upon deployment environment
⢠Allows central ordering of interceptors
28
29. Interceptors â Business Method (Transaction)
@InterceptorBinding @Transactional
public class ShoppingCart { . . . }
@Retention(RUNTIME)
@Target({METHOD,TYPE})
public @interface Transactional { public class ShoppingCart {
} @Transactional public void checkOut() { . . . }
@Interceptor
@Transactional
public class @TransactionInterceptor {
@Resource UserTransaction tx;
@AroundInvoke
public Object manageTransaction(InvocationContext context) {
tx.begin()
context.proceed();
tx.commit();
}
}
http://blogs.sun.com/arungupta/entry/totd_151_transactional_interceptors_using
29
30. Decorators
⢠Complimentary to Interceptors
⢠Apply to beans of a particular bean type
â Semantic aware of the business method
â Implement âbusiness concernsâ
⢠Disabled by default, enabled in âbeans.xmlâ
â May be enabled/disabled at deployment time
⢠@Delegate â injection point for the same type as the beans
they decorate
⢠Interceptors are called before decorators
30
31. Decorator â Sample Code
public interface Account { @Decorator
public BigDecimal getBalance(); public abstract class LargeTransactionDecorator
public User getOwner(); implements Account {
public void withdraw(BigDecimal amount);
public void deposit(BigDecimal amount); @Inject @Delegate @Any Account account;
} @PersistenceContext EntityManager em;
public void withdraw(BigDecimal amount) {
<beans ...
âŚ
<decorators>
}
<class>
org.example.LargeTransactionDecorator public void deposit(BigDecimal amount);
</class> âŚ
}
</decorators>
}
</beans>
31
32. Alternatives
⢠Deployment time polymorphism
⢠@Alternative beans are unavailable for injection, lookup or
EL resolution
â Bean specific to a client module or deployment scenario
⢠Need to be explicitly enabled in âbeans.xmlâ using
<alternatives>/<class>
32
33. Events â More decoupling
⢠Annotation-based event model
â Based upon âObserverâ pattern
⢠A âproducerâ bean fires an event
⢠An âobserverâ bean watches an event
⢠Events can have qualifiers
⢠Transactional event observers
â IN_PROGRESS, AFTER_SUCCESS, AFTER_FAILURE,
AFTER_COMPLETION, BEFORE_COMPLETION
33
35. Stereotypes
⢠Encapsulate architectural patterns or common metadata in a
central place
â Encapsulates properties of the role â scope, interceptor bindings,
qualifiers, etc.
⢠Pre-defined stereotypes - @Interceptor, @Decorator,
@Model
⢠âStereotype stackingâ
35
36. Stereotypes â Sample Code (Pre-defined)
@Named
@RequestScoped
@Stereotype
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface Model {}
⢠Use @Model on JSF âbacking beansâ
36
37. Stereotypes â Sample Code (Make Your Own)
@RequestScoped
@Transactional(requiresNew=true)
@Secure
@Named
@Stereotype
@Retention(RUNTIME)
@Target(TYPE)
public @interface Action {}
37
38. Loose Coupling
⢠Alternatives â deployment time polymorphism
⢠Producer â runtime polymorphism
⢠Interceptors â decouple technical and business concerns
⢠Decorators â decouple business concerns
⢠Event notifications â decouple event producer and
consumers
⢠Contextual lifecycle management decouples bean
lifecycles
38
39. Strong Typing
⢠No String-based identifiers, only type-safe Java constructs
â Dependencies, interceptors, decorators, event produced/consumed, ...
⢠IDEs can provide autocompletion, validation, and refactoring
⢠Lift the semantic level of code
â Make the code more understandable
â @Asynchronous instead of asyncPaymentProcessor
⢠Stereotypes
39
40. CDI & EJB - Typesafety
⢠Java EE resources injected using String-based names (non-
typesafe)
⢠JDBC/JMS resources, EJB references, Persistence
Context/Unit, âŚ
⢠Typesafe dependency injection
⢠Loose coupling, Strong typing
⢠Lesser errors due to typos in String-based names
⢠Easier and better tooling
40
41. CDI & EJB â Stateful Components
⢠Stateful components passed by client in a scope
⢠Explicitly destroy components when the scope is complete
⢠Session bean through CDI is âcontextual instanceâ
⢠CDI runtime creates the instance when needed by the client
⢠CDI runtime destroys the instance when the context ends
41
42. CDI & EJB â As JSF âbacking beanâ
â˘JSF managed beans used as âglueâ to connect with Java EE enterprise
services
⢠EJB may be used as JSF managed beans
⢠No JSF backing beans âglueâ
⢠Brings transactional support to web tier
42
43. CDI & EJB â Enhanced Interceptors
⢠Interceptors only defined for session beans or message
listener methods of MDBs
⢠Enabled statically using âejb-jar.xmlâ or @Interceptors
⢠Typesafe Interceptor bindings on any managed bean
⢠Can be enabled or disabled at deployment using âbeans.xmlâ
⢠Order of interceptors can be controlled using âbeans.xmlâ
43
44. CDI & JSF
⢠Brings transactional support to web tier by allowing EJB as JSF
âbacking beansâ
⢠Built-in stereotypes for ease-of-development - @Model
⢠Integration with Unified Expression Language
â <h:dataTable value=#{cart.lineItems}â var=âitemâ>
⢠Context management complements JSF's component-oriented
model
44
45. CDI & JSF
⢠@ConversationScope holds state with a browser tab in JSF
application
â @Inject Conversation conv;
⢠Transient (default) and long-running conversations
⢠Shopping Cart example
⢠Transient converted to long-running: Conversation.begin/end
⢠@Named enables EL-friendly name
45
46. CDI & JPA
⢠Typesafe dependency injection of PersistenceContext &
PersistenceUnit using @Produces
â Single place to unify all component references
@PersistenceContext(unitName=â...â) EntityManager em;
@Produces @PersistenceContext(unitName=â...â)
CDI @CustomerDatabase EntityManager em;
Qualifier
@Inject @CustomerDatabase EntityManager em;
46
48. CDI & JAX-RS
⢠Manage the lifecycle of JAX-RS resource by CDI
â Annotate a JAX-RS resource with @RequestScoped
⢠@Path to convert class of a managed component into a
root resource class
48
49. CDI & JAX-WS
⢠Typesafe dependency injection of @WebServiceRef using
@Produces
@Produces
@WebServiceRef(lookup="java:app/service/PaymentService")
PaymentService paymentService;
@Inject PaymentService remotePaymentService;
⢠@Inject can be used in Web Service Endpoints & Handlers
⢠Scopes during Web service invocation
â RequestScope during request invocation
â ApplicationScope during any Web service invocation
49
50. Portable Extensions
⢠Key development around Java EE 6 âextensibilityâ theme
⢠Addition of beans, decorators, interceptors, contexts
â OSGi service into Java EE components
â Running CDI in Java SE environment
â TX and Persistence to non-EJB managed beans
⢠Integration with BPM engines
⢠Integration with 3 -party frameworks like Spring, Seam, Wicket
rd
⢠New technology based upon the CDI programming model
50
51. Portable Extension â How to author ?
⢠Implement javax.enterprise.inject.spi.Extension
SPI
â Register service provider
⢠Observe container lifecycle events
â Before/AfterBeanDiscovery, ProcessAnnotatedType
⢠Ways to integrate with container
â Provide beans, interceptors, or decorators
â Satisfy injection points with built-in or wrapped types
â Contribute a scope and context implementation
â Augment or override annotation metadata
51
52. Portable Extensions â Weld Bootstrapping in Java SE
public class HelloWorld {
public void printHello(@Observes ContainerInitialized event,
@Parameters List<String> parameters) {
System.out.println("Hello" + parameters.get(0));
}
}
52
53. Portable Extensions â Weld Logger
public class Checkout {
@Inject Logger log;
public void invoiceItems() {
ShoppingCart cart;
...
log.debug("Items invoiced for {}", cart);
}
}
53
54. Portable Extensions â Typesafe injection of OSGi Service
⢠org.glassfish.osgi-cdi â portable extensionin
GlassFish 3.1
⢠Intercepts deployment of hybrid applications
⢠Discover (using criteria), bind, track, inject the service
⢠Metadata â filter, wait timeouts, dynamic binding
http://blogs.sun.com/sivakumart/entry/typesafe_injection_of_dynamic_osgi
54
61. Summary
⢠Provides standards-based and typesafe dependency injection
in Java EE 6
⢠Integrates well with other Java EE 6 technologies
⢠Portable Extensions facilitate richer programming model
⢠Weld is the Reference Implementation
â Integrated in GlassFish and JBoss
⢠Improving support in IDEs
61