Java EE 6 standards and technologies, such as JSR 299 - Contexts & Dependency Injection, significantly reduce complexity, increase developer productivity and insure your freedom from vendor lock-in.
This Red Hat webinar explains how Java EE 6 can be even simpler than using proprietary legacy frameworks, and take much less time.
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Moving to Java EE 6 and CDI and away from the clutter
1. Move to Java EE 6 and CDI...
...and away from the clutter
Dan Allen
Principal Software Engineer
JBoss by Red Hat
2. Agenda
● Java EE 6: All platform, no clutter
● Java EE's new wiring: JSR-299
● JSR-299 principles
● CDI programming model tour
● CDI extensions
● Weld
● Seam 3
2 Java EE and CDI | Dan Allen
4. Landscaping or a roof garden?
Java EE
Framework X
4 Java EE and CDI | Dan Allen
5. What is Java EE?
● Standard platform comprised of
managed components & services
● Business logic as components
1. Less code
2. Higher signal-to-noise ratio
3. Powerful mechanisms for free
4. Portable knowledge
5 Java EE and CDI | Dan Allen
6. The Java EE we always wanted
● No-interface EJBs
● Embeddable EJB container
● Simplified packaging
● EJBs in a WAR
● POJOs, finally! Java EE
● Annotations + partial descriptors 6
● No more XML-hell XML
● Web profile
● GTD in Java EE
6 Java EE and CDI | Dan Allen
7. Web profile stack (read as: all you need)
● Persistence ● Presentation
● JPA 2.0 ● JSF 2.0
● JTA 1.1 ● Servlet 3.0
● Component model ● JBoss AS extras
● EJB 3.1 (lite) ● JMS 1.1
● CDI 1.0 ● JAX-RS 1.1
● Bean Validation 1.0
7 Java EE and CDI | Dan Allen
8. Technology terminology
● JSR-299 (CDI)
● Contexts & Dependency Injection for the
Java EE Platform
● Weld
● JSR-299 Reference Implementation & TCK
● Extended CDI support (Servlets, Java SE)
● Portable CDI enhancements and utilities
● Seam 3
● Portable extensions for Java EE
● Portable integrations with non-Java EE technologies
8 Java EE and CDI | Dan Allen
9. Stated goal of JSR-299
Web tier Transactional tier
(JSF) (EJB)
9 Java EE and CDI | Dan Allen
10. What CDI provides
● Services for Java EE components
● Lifecycle management of stateful beans bound to
well-defined contexts (including conversation context)
● A type-safe approach to dependency injection
● Interaction via an event notification facility
● Reduced coupling between interceptors and beans
● Decorators, which intercept specific bean instances
● Unified EL integration (bean names)
● SPI for developing extensions for the Java EE platform
● Java EE architecture flexible, portable, extensible
10 Java EE and CDI | Dan Allen
11. What CDI provides
● Services for Java EE components
● Lifecycle management of stateful beans bound to
well-defined contexts (including conversation context)
● A type-safe approach to dependency injection
● Interaction via an event notification facility
● Reduced coupling between interceptors and beans
● Decorators, which intercept specific bean instances
● Unified EL integration (bean names)
● SPI for developing extensions for the Java EE platform
● Java EE architecture flexible, portable, extensible
11 Java EE and CDI | Dan Allen
12. CDI: The big picture
● Fill in
● Catalyze
● Evolve
12 Java EE and CDI | Dan Allen
13. Whoa, why dependency injection?
● Weakest aspect of Java EE 5
● Closed set of injectable resources
● @EJB
● @PersistenceContext, @PersistenceUnit
● @Resource (e.g., DataSource, UserTransaction)
● Name-based injection is fragile
● Lacked rules
13 Java EE and CDI | Dan Allen
14. Leverage and extend Java’s type system
@Annotation <TypeParam>
This information is pretty useful!
Type
14 Java EE and CDI | Dan Allen
15. JSR-299 theme
@Produces @WishList
Loose coupling... List<Product> getWishList()
Event<Order>
@InterceptorBinding
@Inject @UserDatabase EntityManager
@Observes
@Qualifier ...with strong typing
15 Java EE and CDI | Dan Allen
16. Loose coupling
●
Decouple server and client
● Contract based on well-defined types and “qualifiers”
●
Decouple lifecycle of collaborating components
● Stateful components interact like services
●
Decouple orthogonal concerns (AOP)
● Interceptors & decorators
●
Decouple message producer from consumer
● Events
16 Java EE and CDI | Dan Allen
17. Strong typing
● Type-based injection
● Eliminate reliance on string-based names
● Refactor friendly
● Compiler can detect typing errors
● No special authoring tools required
● Casting mostly eliminated
● Semantic code errors detected at application startup
● Enables strong tooling
● Preemptively detect errors
● Navigate relationships
17 Java EE and CDI | Dan Allen
18. Strong typing = strong tooling
CDI tools available in JBoss Tools 3.2 - http://jboss.org/tools
18 Java EE and CDI | Dan Allen
19. Who's bean is it anyway?
● Everyone throwing around this term “bean”
● JSF
● EJB
● Seam
● Spring
● Guice
● Web Beans
● Need a “unified bean definition”
19 Java EE and CDI | Dan Allen
20. Managed bean specification
● Common bean definition
● Instances managed by Managed
the container Beans
● Common services
● Lifecycle callbacks
● Resource injections
● Interceptors JSF EJB CDI JAX-RS
● Foundation spec
How managed beans evolved: http://www.infoq.com/news/2009/11/weld10
20 Java EE and CDI | Dan Allen
21. CDI bean ingredients
● Set of bean types
DI contract
● Set of qualifiers
● Scope
● Bean EL name (optional)
● Set of interceptor bindings
● Alternative classification
● Bean implementation class
Auto-discovered!
21 Java EE and CDI | Dan Allen
22. Welcome to CDI, managed bean!
public class Welcome {
public String buildPhrase(String city) {
return "Welcome to " + city + "!";
}
}
22 Java EE and CDI | Dan Allen
23. Welcome to CDI, EJB 3.1 session bean!
@Stateless public class Welcome {
public String buildPhrase(String city) {
return "Welcome to " + city + "!";
}
}
23 Java EE and CDI | Dan Allen
24. When is a bean recognized?
● Bean archive (WAR) ● Bean archive (JAR)
beans.xml can be empty!
24 Java EE and CDI | Dan Allen
25. Injection 101
public class Greeter {
@Inject Welcome w;
public void welcome() {
System.out.println(
w.buildPhrase("New York"));
}
}
25 Java EE and CDI | Dan Allen
26. Where can it be injected?
● Field
● Method parameter
● Constructor*
● Initializer
● Producer
● Observer
26 Java EE and CDI | Dan Allen
27. What can be injected?
Managed bean
Object returned by producer
EJB session bean (local or remote)
Java EE resource (DataSource, JMS destination, etc)
JTA UserTransaction
Persistence unit or context
Security principle
Bean Validation factory
Web service reference
Additional resources introduced through SPI
27 Java EE and CDI | Dan Allen
28. The bean vs “the other implementation”
public class Welcome {
public String buildPhrase(String city) {
return "Welcome to " + city + "!";
}
}
public class TranslatingWelcome extends Welcome {
@Inject GoogleTranslator translator;
public String buildPhrase(String city) {
return translator.translate(
"Welcome to " + city + "!");
}
}
28 Java EE and CDI | Dan Allen
29. Quiz: Which implementation gets injected?
public class Greeter {
private Welcome welcome;
@Inject
void init(Welcome welcome) {
this.welcome = welcome;
}
...
}
It's ambiguous!
29 Java EE and CDI | Dan Allen
30. Working out an ambiguous resolution
● Qualifier
● Alternative
● Veto (or hide)
30 Java EE and CDI | Dan Allen
31. qualifier
n. an annotation used to resolve an API
implementation variant at an injection point
31 Java EE and CDI | Dan Allen
32. Defining a qualifier
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Translating {}
@interface = annotation
@interface = annotation
32 Java EE and CDI | Dan Allen
33. Qualifying an implementation
@Translating
public class TranslatingWelcome extends Welcome {
@Inject GoogleTranslator translator;
public String buildPhrase(String city) {
return translator.translate(
"Welcome to " + city + "!");
}
}
● Qualifiers:
● makes type more specific
● assign semantic meaning
33 Java EE and CDI | Dan Allen
34. Qualifier as a “binding type”
34 Java EE and CDI | Dan Allen
35. Explicitly request qualified interface
public class Greeter {
private Welcome welcome; No reference to implementation class!
No reference to implementation class!
@Inject
void init(@Translating Welcome welcome) {
this.welcome = welcome;
}
public void welcomeVisitors() {
System.out.println(
welcome.buildPhrase("New York"));
}
}
35 Java EE and CDI | Dan Allen
36. Alternative bean
● Swap replacement implementation per deployment
● Replaces bean and its producers
● Activated in /META-INF/beans.xml
● Disabled by default
In order words, a replacement
36 Java EE and CDI | Dan Allen
37. Defining an alternative
@Alternative
public class TranslatingWelcome extends Welcome {
@Inject GoogleTranslator translator;
public String buildPhrase(String city) {
return translator.translate(
"Welcome to " + city + "!");
}
}
37 Java EE and CDI | Dan Allen
38. Substituting the alternative using beans.xml
<beans>
<alternatives>
<class>com.acme.TranslatingWelcome</class>
</alternatives>
</beans>
38 Java EE and CDI | Dan Allen
39. Assigning a bean (EL) name
@Named("greeter")
public class Greeter {
private Welcome welcome;
@Inject
void init(Welcome welcome) {
this.welcome = welcome;
}
public void welcomeVisitors() {
System.out.println(
welcome.buildPhrase("New York"));
}
}
39 Java EE and CDI | Dan Allen
40. Assigning a bean (EL) name by convention
@Named
public class Greeter {
private Welcome welcome; Bean name is decapitalized
Bean name is decapitalized
simple class name
simple class name
@Inject
void init(Welcome welcome) {
this.welcome = welcome;
}
public void welcomeVisitors() {
System.out.println(
welcome.buildPhrase("New York"));
}
}
40 Java EE and CDI | Dan Allen
41. Welcome to CDI, JSF!
● Use the bean directly in the JSF view
<h:form>
<h:commandButton value="Welcome visitors"
action="#{greeter.welcomeVisitors}"/>
</h:form>
41 Java EE and CDI | Dan Allen
42. JSF
managed
beans
CDI
42 Java EE and CDI | Dan Allen
43. Stashing the bean in a context
Bean stored for duration of request
Bean stored for duration of request
@Named
@RequestScoped
public class Greeter {
@Inject private Welcome w;
private String city;
public String getCity() { return city; }
public void setCity(String city) {
this.city = city;
}
public void welcomeVisitors() {
System.out.println(w.buildPhrase(city));
}
}
43 Java EE and CDI | Dan Allen
44. Collapsing layers with state management
● Now it’s possible for bean to hold state
<h:form>
<h:inputText value="#{greeter.city}"/>
<h:commandButton value="Welcome visitors"
action="#{greeter.welcomeVisitors}"/>
</h:form>
New York
Prints:
Welcome to New York!
44 Java EE and CDI | Dan Allen
45. Mission accomplished: We have a deal!
Web tier Business tier
(JSF) (managed bean)
45 Java EE and CDI | Dan Allen
46. Scope types and contexts
● @Dependent – Default scope
● Bound to lifecycle of bean holding reference
● @ApplicationScoped
● @RequestScoped Servlet scopes
● @SessionScoped
● @ConversationScoped – JSF scope
● Request ≤ Conversation ≪ Session
● Custom scopes
● Define scope type annotation (e.g., @FlashScoped)
● Implement the context API in an extension
46 Java EE and CDI | Dan Allen
47. Scope transparency
● Scopes not visible to client (no coupling)
● Scoped beans are proxied for thread safety
47 Java EE and CDI | Dan Allen
48. producer method
n. a method whose return value produces
an injectable object
48 Java EE and CDI | Dan Allen
49. Producer method examples
@Produces @RequestScoped
public FacesContext getFacesContext() { From non-bean
From non-bean
return FacesContext.getInstance();
}
@Produces
public PaymentProcessor getPaymentProcessor(
@Synchronous PaymentProcessor sync,
Runtime selection
Runtime selection
@Asynchronous PaymentProcessor async) {
return isSynchronous() ? sync : async;
}
@Produces @SessionScoped @WishList Dynamic result set
Dynamic result set
public List<Product> getWishList() {
return em.createQuery("...").getResultList();
}
49 Java EE and CDI | Dan Allen
50. Injecting producer return values
@Inject FacesContext ctx;
@Inject PaymentProcessor pp;
@Inject @WishList List<Product> wishlist;
Origin of product is hidden at injection point
50 Java EE and CDI | Dan Allen
51. Bridging Java EE resources to CDI
public class UserEntityManagerProducer {
@Produces @InventoryRepository
@PersistenceContext(unitName = "inventory")
private EntityManager inventory;
}
Producer fields can promote
Producer fields can promote
Java EE resources as beans
Java EE resources as beans
public class PricesTopicProducer {
@Produces @Prices
@Resource(name = "java:global/env/jms/Prices")
private Topic pricesTopic;
}
51 Java EE and CDI | Dan Allen
52. Injecting resources in type-safe way
public class UserManager {
@Inject @InventoryRepository
EntityManager inventory;
...
}
Eliminates string-based
Eliminates string-based
names at injection points
names at injection points
public class StockDisplay {
@Inject @Prices
Topic pricesTopic;
...
}
52 Java EE and CDI | Dan Allen
53. Java EE 6: Simple, clean and integrated
@Stateless
@Path("/product")
public class ProductResourceHandler {
@Inject @InventoryDatabase EntityManager em;
@GET @Path("/{id:[1-9][0-9]+}")
@Produces("application/xml")
public Product getProduct(@PathParam("id")
Long id) {
return em.find(Product.class, id);
}
}
53 Java EE and CDI | Dan Allen
54. Rethinking interceptors
@Interceptors(
SecurityInterceptor.class,
TransactionInterceptor.class,
LoggingInterceptor.class
)
@Stateful public class BusinessComponent {
...
}
Um, what's the point?
54 Java EE and CDI | Dan Allen
55. Define an interceptor binding type
@InterceptorBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secure {}
55 Java EE and CDI | Dan Allen
56. Mark the interceptor implementation
@Secure
@Interceptor
public class SecurityInterceptor {
@AroundInvoke
public Object aroundInvoke(InvocationContext ctx)
throws Exception {
// enforce security...
ctx.proceed();
}
}
56 Java EE and CDI | Dan Allen
57. Interceptor wiring with proper semantics
@Secure
public class AccountManager {
public boolean transfer(Account a, Account b) {
...
}
}
57 Java EE and CDI | Dan Allen
58. Enabling interceptors using beans.xml
<beans>
<interceptors>
<class>com.acme.SecurityInterceptor</class>
<class>com.acme.TransactionInterceptor</class>
</interceptors>
</beans>
Interceptors applied in order listed
Interceptors applied in order listed
58 Java EE and CDI | Dan Allen
59. Annotation jam!
@Secure
@Transactional
@RequestScoped
@Named
public class AccountManager {
public boolean transfer(Account a, Account b) {
...
}
}
59 Java EE and CDI | Dan Allen
60. stereotype
n. an annotation used to group common
architectural patterns (recurring roles)
60 Java EE and CDI | Dan Allen
61. Define a stereotype to bundle annotations
@Secure
@Transactional
@RequestScoped
@Named
@Stereotype
@Retention(RUNTIME)
@Target(TYPE)
public @interface BusinessComponent {}
61 Java EE and CDI | Dan Allen
62. Using a stereotype
@BusinessComponent
public class AccountManager {
public boolean transfer(Account a, Account b) {
...
}
}
62 Java EE and CDI | Dan Allen
63. Portable extensions
● Auto-discovered
Se
rvic
● Integrate with the container by: eP
rov
ide
r Inte
rfac
● Providing beans, interceptors or decorators e (S
PI )
● Injecting dependencies into its own objects
● Contributing a scope and context implementation
● Augmenting or overriding annotation metadata
● Observe container lifecycle events
● Before/after bean discovery
● After deployment validation
● Processing bean, producer, observer, or injection target
63 Java EE and CDI | Dan Allen
65. Weld: The axis of CDI
Implement Validate
(RI) (TCK)
Reach Improve
(Servlet, SE) (Extensions)
65 Java EE and CDI | Dan Allen
66. JSR-299 RI & TCK
● Reference Implementation (RI)
● Technology Compatibility Kit (TCK)
● Developer-oriented reference guide
Other implementations:
●
● Apache OpenWebBeans
●
● Resin CanDI
66 Java EE and CDI | Dan Allen
67. Weld “X”
● A library of Generally Useful Stuff™
● Enhancements to CDI programming model
● Bean discovery control
● Injectable logger and resource loader
● EL evaluator and more...
● Utilities for framework & extension writers
● Annotation metadata utilties
● JavaBean inspectors
● BeanManager locator and more...
67 Java EE and CDI | Dan Allen
69. Seam’s mission statement
To provide a fully integrated development
platform for building rich Internet applications
based upon the Java EE environment.
69 Java EE and CDI | Dan Allen
71. Portable modules
● Module per domain or integration
● Independently...
● lead
● versioned
● released
● Per-module structure
● Based on CDI
● API & implementation
● Reference documentation & examples
71 Java EE and CDI | Dan Allen
73. What's on the menu so far?
● Drools ● JavaScript remoting
● jBPM ● Security
● JMS ● Servlet
● Faces ● Wicket
● International ● XML configuration
● Persistence ● Exception handling
...and more
http://github.com/seam
73 Java EE and CDI | Dan Allen
74. XML-based configuration
<beans ...
xmlns:app="java:urn:com.acme">
<app:TranslatingWelcome>
<app:Translating/>
<app:defaultLocale>en-US</app:defaultLocale>
</app:TranslatingWelcome>
</beans>
● Define, specialize or override beans
● Add annotations (qualifiers, interceptor bindings, ...)
● Assign initial property values
74 Java EE and CDI | Dan Allen
75. Arquillian: Container-oriented testing for Java EE
@RunWith(Arquillian.class)
public class GreeterTestCase {
@Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Greeter.class, GreeterBean.class);
}
@EJB private Greeter greeter;
@Test
public void shouldBeAbleToInvokeEJB() throws Exception {
assertEquals("Hello, Earthlings", greeter.greet("Earthlings"));
}
} http://jboss.org/arquillian
75 Java EE and CDI | Dan Allen
76. Summary
● Java EE 6 is leaner and more productive
● JSR-299 (CDI) provides a set of services for Java EE
● Bridges JSF and EJB
● Offers loose coupling with strong typing
● Provides a type-based event bus
● Catalyzed change in Java EE 6
● Introduced SPI for third-party integration with Java EE
● Weld: JSR-299 reference implementation & add-ons
● Seam 3: Portable extensions for Java EE
76 Java EE and CDI | Dan Allen
77. How do I get started?
● Download a Java EE 6 container
● JBoss AS 6 ● GlassFish V3
http://jboss.org/jbossas http://glassfish.org
● Generate a Java EE project using a Maven archetype
● http://tinyurl.com/goweld
● Read the Weld reference guide
● http://tinyurl.com/weld-reference-101
● Browse the CDI API docs
● http://docs.jboss.org/cdi/api/latest/
● Check out the Seam 3 project
● http://seamframework.org/Seam3
77 Java EE and CDI | Dan Allen
78. Say goodbye to the clutter !
Dan Allen
Principal Software Engineer
JBoss by Red Hat
http://seamframework.org/Weld
http://seamframework.org/Seam3