SlideShare a Scribd company logo
Java EE 6 CDI Integrates
   with Spring & JSF
      on Java EE 5
  Jiayun Zhou jiayun@jiayun.org
           2012/03/17
             TWJUG
先鋒的第一次 迎新再對折
CDI
• JSR 299: Contexts and Dependency
  Injection
• Java EE 6




                                     3
Java EE 6 CDI Integrates with Spring & JSF
Copyright by IISI. All rights reserved   5
Copyright by IISI. All rights reserved   6
• http://www.slideshare.net/johaneltes/java-ee6-cdi
Inversion of Control
          vs
Dependency Injection
IoC

Inversion of Control




                       9
IoC

Inversion of Control Flow




                            10
Martin Fowler




                11
Command Line
#ruby
puts 'What is your name?'
name = gets
process_name(name)
puts 'What is your quest?'
quest = gets
process_quest(quest)

                             12
GUI
require 'tk'
root = TkRoot.new()
name_label = TkLabel.new() {text "What is Your Name?"}
name_label.pack
name = TkEntry.new(root).pack
name.bind("FocusOut") {process_name(name)}
quest_label = TkLabel.new() {text "What is Your Quest?"}
quest_label.pack
quest = TkEntry.new(root).pack
quest.bind("FocusOut") {process_quest(quest)}
Tk.mainloop()



                                                           13
Hollywood Principle

Don’t call us, we’ll call you.




                                 14
Ex. HttpSessionListener
• sessionCreated()
• sessionDestroyed()




                           15
Ex. Template Method Pattern




                              16
Dependency Injection

     One Form of IoC




                       17
class MovieLister...
   public Movie[] moviesDirectedBy(String arg) {
     List allMovies = finder.findAll();
     for (Iterator it = allMovies.iterator(); it.hasNext();) {
        Movie movie = (Movie) it.next();
        if (!movie.getDirector().equals(arg)) it.remove();
     }
     return (Movie[]) allMovies.toArray(new
    Movie[allMovies.size()]);
   }

                                                                 18
public interface MovieFinder {
  List findAll();
}




                                 19
class MovieLister...
 private MovieFinder finder;
 public MovieLister() {
   finder = new
   ColonDelimitedMovieFinder("movies1.txt");
 }



                                               20
21
22
Spring Stereotype
• @Component
• @Repository
• @Service
• @Controller


                        23
@Repository
class ColonMovieFinder...
   public void setFilename(String filename) {
     this.filename = filename;
   }




                                                24
Spring @Autowired
class MovieLister...
 private MovieFinder finder;

 @Autowired
 public void setFinder(MovieFinder finder) {
   this.finder = finder;
 }

                                               25
CODI
• Apache MyFaces Extensions CDI
  project




                                  26
同時作業Demo




           27
同時作業Demo




           28
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
Weld
• CDI Implementation
• Included in WebLogic 12c
• Running on WebLogic 11g




                             31
Libraries
<dependency>
         <groupId>org.jboss.weld.servlet</groupId>
         <artifactId>weld-servlet</artifactId>
</dependency>

<dependency>
         <groupId>org.apache.myfaces.extensions.cdi.bundles</groupId>
         <artifactId>myfaces-extcdi-bundle-jsf20</artifactId>
</dependency>
<dependency>
         <groupId>org.apache.myfaces.extensions.cdi.modules.jee5-support</groupId>
         <artifactId>myfaces-extcdi-jee5-weld-support</artifactId>
         <scope>runtime</scope>
</dependency>
Libraries
<dependency>
         <groupId>org.cdisource.springbridge</groupId>
         <artifactId>springbridge</artifactId>
</dependency>
<dependency>
         <groupId>org.cdisource.beancontainer</groupId>
         <artifactId>beancontainer-weld-impl</artifactId>
</dependency>
web.xml
<listener>
       <listener-
class>org.cdisource.springintegration.servletsupport.ApplicationC
ontextFinderServletContextListener</listener-class>
</listener>
<listener>
       <listener-
class>org.apache.myfaces.extensions.cdi.weld.startup.WeldAwareCon
figurationListener</listener-class>
</listener>
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
      http://java.sun.com/xml/ns/javaee
      http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

</beans>

• src/main/webapp/WEB-INF
• src/main/resources
都要放
Spring Bridge
• src/main/resources/META-
  INF/services/javax.enterprise.inject.spi.Extension
• 內容:
  org.cdisource.springintegration.SpringIntegration
  Extention

• Service Provider Interface (SPI)
  http://docs.oracle.com/javase/7/docs/api/java/
  util/ServiceLoader.html
Spring 掃描排除 CDI Bean
<context:component-scan base-
package="com.xxx">
     <context:exclude-filter type="regex"
expression="com.xxx.*.web.*" />
</context:component-scan>
Controller 引用 Service
@WindowScoped
@XxxExceptionCatcher
@Named("xxxController")
public class XxxController implements Serializable {

    @Inject
    @Spring(name = "registerService")
    private transient RegisterService registerService;




                                                   38
CDI AOP (annotation)
@InterceptorBinding
@Target({ ElementType.TYPE,
ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface XxxExceptionCatcher {

}
CDI AOP (interceptor)
@Interceptor
@RisExceptionCatcher
public class XxxExceptionInterceptor implements
Serializable {

      @AroundInvoke
      public Object catchException(InvocationContext
ctx) throws Exception {
CDI AOP (beans.xml)
<interceptors>
      <class>com.xxx.XxxExceptionInterceptor</class>
</interceptors>
Logger
@WindowScoped
@XxxExceptionCatcher
@Named("xxxController")
public class XxxController implements Serializable {

     @Inject
     private Logger logger;




• http://www.slf4j.org/faq.html#declared_static



                                                   42
LoggerFactory
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

import org.slf4j.Logger;

public class LoggerFactory {

    @Produces
    Logger createLogger(InjectionPoint injectionPoint) {
        String name =
injectionPoint.getMember().getDeclaringClass().getName();
        return org.slf4j.LoggerFactory.getLogger(name);
    }

}


                                                        43
References
• http://seamframework.org/Weld/WeldDocum
  entation
• https://cwiki.apache.org/confluence/display/E
  XTCDI/Documentation




                                              44
Sample Code
• https://github.com/jiayun/cdisource
• https://github.com/jiayun/java_misc_samples




                                            45
WebLogic 12c
• 必須解壓 CODI jar 到 WEB-INF/classes
• 已回報給 Oracle
- Thank You -

More Related Content

PDF
Akka Cluster in Java - JCConf 2015
PPTX
Spring Boot
PPTX
Spring & Hibernate
PPTX
Spring boot Introduction
ODP
Spring 4 final xtr_presentation
PDF
Node.js vs Play Framework (with Japanese subtitles)
PDF
Java(ee) mongo db applications in the cloud
PDF
Web application development using Play Framework (with Java)
Akka Cluster in Java - JCConf 2015
Spring Boot
Spring & Hibernate
Spring boot Introduction
Spring 4 final xtr_presentation
Node.js vs Play Framework (with Japanese subtitles)
Java(ee) mongo db applications in the cloud
Web application development using Play Framework (with Java)

What's hot (20)

PDF
REST APIs with Spring
PDF
Spring 4 on Java 8 by Juergen Hoeller
PDF
Play vs Rails
PPTX
Java Libraries You Can’t Afford to Miss
PDF
Java Libraries You Can’t Afford to Miss
PPTX
From JavaEE to AngularJS
PDF
CQ5 QueryBuilder - .adaptTo(Berlin) 2011
PDF
The internet of (lego) trains
PDF
the Spring 4 update
PDF
Fifty Features of Java EE 7 in 50 Minutes
PDF
Asynchronous web apps with the Play Framework 2.0
PDF
Short intro to scala and the play framework
PDF
Apache Aries Overview
PPTX
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
PPTX
Faster Java EE Builds with Gradle
PPT
Intoduction to Play Framework
PDF
Greach 2019 - Creating Micronaut Configurations
PPTX
The Past Year in Spring for Apache Geode
PDF
Apache DeltaSpike the CDI toolbox
PPTX
How to customize Spring Boot?
REST APIs with Spring
Spring 4 on Java 8 by Juergen Hoeller
Play vs Rails
Java Libraries You Can’t Afford to Miss
Java Libraries You Can’t Afford to Miss
From JavaEE to AngularJS
CQ5 QueryBuilder - .adaptTo(Berlin) 2011
The internet of (lego) trains
the Spring 4 update
Fifty Features of Java EE 7 in 50 Minutes
Asynchronous web apps with the Play Framework 2.0
Short intro to scala and the play framework
Apache Aries Overview
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
Faster Java EE Builds with Gradle
Intoduction to Play Framework
Greach 2019 - Creating Micronaut Configurations
The Past Year in Spring for Apache Geode
Apache DeltaSpike the CDI toolbox
How to customize Spring Boot?
Ad

Viewers also liked (10)

PPTX
Java EE 6
PDF
Moving to Java EE 6 and CDI and away from the clutter
PDF
CDI and Seam 3: an Exciting New Landscape for Java EE Development
PDF
Designing Java EE Applications in the Age of CDI
PDF
What we can expect from Java 9 by Ivan Krylov
PDF
CDI, Weld and the future of Seam
PDF
Introduction to cdi given at java one 2014
PDF
Extending Java EE with CDI and JBoss Forge
PDF
Java one 2015 [con3339]
PDF
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Java EE 6
Moving to Java EE 6 and CDI and away from the clutter
CDI and Seam 3: an Exciting New Landscape for Java EE Development
Designing Java EE Applications in the Age of CDI
What we can expect from Java 9 by Ivan Krylov
CDI, Weld and the future of Seam
Introduction to cdi given at java one 2014
Extending Java EE with CDI and JBoss Forge
Java one 2015 [con3339]
Developing Modern Java Web Applications with Java EE 7 and AngularJS
Ad

Similar to Java EE 6 CDI Integrates with Spring & JSF (20)

PDF
Spring framework core
PPTX
A brief overview of java frameworks
PPTX
Contexts and Dependency Injection
PDF
Invoke dynamite in Java EE with invoke dynamic
PDF
Everything as a Code / Александр Тарасов (Одноклассники)
PDF
Everything as a code
PDF
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
PDF
What to expect from Java 9
PPTX
Js tacktalk team dev js testing performance
PDF
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
PDF
What's New In Apache Lenya 1.4
KEY
Curator intro
PPTX
Cloud nativeworkshop
PDF
Integration tests: use the containers, Luke!
PDF
Atlassian Groovy Plugins
PDF
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
PDF
Exploring lambdas and invokedynamic for embedded systems
PDF
Arquillian Constellation
PDF
Eric Lafortune - The Jack and Jill build system
PDF
Writing Plugged-in Java EE Apps: Jason Lee
Spring framework core
A brief overview of java frameworks
Contexts and Dependency Injection
Invoke dynamite in Java EE with invoke dynamic
Everything as a Code / Александр Тарасов (Одноклассники)
Everything as a code
A Cocktail of Guice and Seam, the missing ingredients for Java EE 6
What to expect from Java 9
Js tacktalk team dev js testing performance
TechDays 2016 - Developing websites using asp.net core mvc6 and entity framew...
What's New In Apache Lenya 1.4
Curator intro
Cloud nativeworkshop
Integration tests: use the containers, Luke!
Atlassian Groovy Plugins
Kotlin+MicroProfile: Ensinando 20 anos para uma linguagem nova
Exploring lambdas and invokedynamic for embedded systems
Arquillian Constellation
Eric Lafortune - The Jack and Jill build system
Writing Plugged-in Java EE Apps: Jason Lee

Recently uploaded (20)

PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
KodekX | Application Modernization Development
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
Chapter 3 Spatial Domain Image Processing.pdf
Big Data Technologies - Introduction.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Per capita expenditure prediction using model stacking based on satellite ima...
MIND Revenue Release Quarter 2 2025 Press Release
Dropbox Q2 2025 Financial Results & Investor Presentation
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
KodekX | Application Modernization Development
NewMind AI Weekly Chronicles - August'25 Week I
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Mobile App Security Testing_ A Comprehensive Guide.pdf
sap open course for s4hana steps from ECC to s4
Understanding_Digital_Forensics_Presentation.pptx
MYSQL Presentation for SQL database connectivity
Advanced methodologies resolving dimensionality complications for autism neur...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Reach Out and Touch Someone: Haptics and Empathic Computing

Java EE 6 CDI Integrates with Spring & JSF