KEMBAR78
Java EE 6 CDI Integrates with Spring & JSF | PDF
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
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
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 -

Java EE 6 CDI Integrates with Spring & JSF