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
Unlocking AI with Model Context Protocol (MCP)
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
A Presentation on Artificial Intelligence
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Electronic commerce courselecture one. Pdf
PPT
Teaching material agriculture food technology
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PDF
Approach and Philosophy of On baking technology
PPTX
Spectroscopy.pptx food analysis technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
NewMind AI Weekly Chronicles - August'25-Week II
Unlocking AI with Model Context Protocol (MCP)
Dropbox Q2 2025 Financial Results & Investor Presentation
A Presentation on Artificial Intelligence
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
20250228 LYD VKU AI Blended-Learning.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
SOPHOS-XG Firewall Administrator PPT.pptx
Electronic commerce courselecture one. Pdf
Teaching material agriculture food technology
Diabetes mellitus diagnosis method based random forest with bat algorithm
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Approach and Philosophy of On baking technology
Spectroscopy.pptx food analysis technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Spectral efficient network and resource selection model in 5G networks
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
NewMind AI Weekly Chronicles - August'25-Week II

Java EE 6 CDI Integrates with Spring & JSF