SlideShare a Scribd company logo
1 of 22
Download to read offline
Modern Component Design with Spring 3

Jürgen Höller, Principal Engineer, SpringSource




                                                                               CONFIDENTIAL

                                                  © 2010 SpringSource, A division of VMware. All rights reserved
Spring 3.0 – Component Model Revisited
 Powerful annotated component model
 • stereotypes, factory methods, JSR-330
 Spring Expression Language
 • Unified EL++
 Comprehensive REST support
 • and other Spring @MVC additions
 Support for Portlet 2.0 request types
 • action/render/event/resource mappings
 Declarative validation and formatting
 • integration with JSR-303 Bean Validation
 Scheduling enhancements
 • scheduling annotation with cron support



                                     CONFIDENTIAL   2
Enhanced Stereotype Model
 Powerful options for custom annotations
    • combining meta-annotations e.g. on stereotype
    • automatically detected (no configuration necessary!)


@Service
@Scope("request")
@Transactional(rollbackFor=Exception.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyService {}


@MyService
public class BookAdminService {
       …
}

                                        CONFIDENTIAL         3
Annotated Factory Methods
 Spring 3.0 includes the core functionality of the former
    Spring JavaConfig project
    • configuration classes defining managed beans
    • common handling of annotated factory methods


@Bean @Primary @Lazy
public BookAdminService bookAdminService() {
       MyBookAdminService service = new MyBookAdminService();
       service.setDataSource(…);
       return service;
}




                                      CONFIDENTIAL              4
Standardized Annotations

@ManagedBean
public class MyBookAdminService implements BookAdminService {


    @Inject
    public MyBookAdminService(AccountRepository ar) {
        …
    }


    @TransactionAttribute
    public BookUpdate updateBook(Addendum addendum) {
        …
    }
}


                            CONFIDENTIAL                        5
JSR-330 and Co
 @javax.inject.Inject is part of JSR-330
 • "Dependency Injection for Java"
 • also defines @Qualifier semantics
 • and a Provider interface


 @javax.annotation.ManagedBean is part of JSR-250 v1.1
 • driven by the Java EE 6 specification
 • can be detected through classpath scanning


 @javax.ejb.TransactionAttribute is part of the EJB 3.0/3.1
 specification
 • also supported for Spring beans



                                       CONFIDENTIAL            6
EL in XML Bean Definitions

<bean class="mycompany.BookTestDatabase">


    <property name="databaseName"
        value="#{systemProperties.databaseName}"/>


    <property name="keyGenerator"
        value="#{strategyBean.databaseKeyGenerator}"/>


</bean>




                            CONFIDENTIAL                 7
EL in Component Annotations

@Repository
public class BookTestDatabase {


    @Value("#{systemProperties.databaseName}")
    public void setDatabaseName(String dbName) { … }


    @Value("#{strategyBean.databaseKeyGenerator}")
    public void setKeyGenerator(KeyGenerator kg) { … }


}




                            CONFIDENTIAL                 8
REST in MVC - @PathVariable



  http://mybookstore.com/books/12345

  @RequestMapping(value = "/books/{id}", method = GET)
  public Book findBook(@PathVariable("id") long id) {
      return this.bookAdminService.findBook(id);
  }




                           CONFIDENTIAL                  9
Portlet 2.0 Support in MVC
@Controller
@RequestMapping("EDIT")
public class MyPortletController {


    @ActionMapping("delete")
    public void removeBook(@RequestParam("book") String bookId) {
        this.myService.deleteBook(bookId);
    }


    @EventMapping("BookUpdate")
    public void updateBook(BookUpdateEvent bookUpdate) {
        // extract book entity data from event payload object
        this.myService.updateBook(…);
    }
}
                                  CONFIDENTIAL                      10
Declarative Model Validation
public class Book {
     @NotNull
     @Past
     private Date releaseDate;
}


@RequestMapping("/books/new")
public void newBook(@Valid Book book) { … }


 JSR-303 "Bean Validation" as the common ground
 Spring 3.0 fully supports JSR-303 for MVC data binding
 Same metadata can be used for persisting, rendering, etc



                                     CONFIDENTIAL            11
Conversion and Formatting
 Spring 3.0 features a revised binding and type conversion
    infrastructure
    • stateless Java 5+ type converters and formatters
    • annotation-driven number/date formatting


public class Book {
       @NotNull
       @Past
       @DateTimeFormat(iso=ISO.DATE)
       private Date releaseDate;
}




                                        CONFIDENTIAL          12
Scheduling Enhancements
 Spring 3.0 introduces a major overhaul of the scheduling
    package
    • TaskScheduler interface with Trigger abstraction
    • XML scheduling namespace with cron support
    • @Async annotation for asynchronous user methods
    • @Scheduled annotation for cron-triggered methods


@Scheduled(cron = "0 0 12 * * ?")
public void performTempFileCleanup() {
       ...
}




                                      CONFIDENTIAL           13
Related Java EE 6 Specifications
 Java EE 6 API support in Spring Framework 3.0
 • several specifications adopted into the Spring component model


 Integration with JPA 2.0
 • support for query builder, native delegates, etc
 Integration with JSF 2.0
 • full compatibility as a managed bean facility


 JSR-303 Bean Validation integration
 • through Hibernate Validator 4.1
 JSR-330: common dependency injection annotations
 • natively supported by Spring itself


                                         CONFIDENTIAL               14
Spring 3.1 – Component Model Enhancements
 Environment profiles for bean definitions
 Java-based application configuration
 "c:" namespace for XML configuration
 Declarative caching




                                CONFIDENTIAL   15
Environment Profiles
<beans profile="production">
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
   <property name="driverClass" value="${database.driver}"/>
   <property name="jdbcUrl" value="${database.url}"/>
   <property name="username" value="${database.username}"/>
   <property name="password" value="${database.password}"/>
  </bean>
</beans>


<beans profile="embedded">
  <jdbc:embedded-database id="dataSource" type="H2">
    <jdbc:script location="/WEB-INF/database/schema-member.sql"/>
    <jdbc:script location="/WEB-INF/database/schema-activity.sql"/>
    <jdbc:script location="/WEB-INF/database/schema-event.sql"/>
    <jdbc:script location="/WEB-INF/database/data.sql"/>
  </jdbc:embedded-database>
</beans>




                                   CONFIDENTIAL                           16
Environment Configuration
 Environment association of specific bean definitions
 • XML 'profile' attribute on <beans> element
 • @Profile annotation on configuration classes
 • @Profile annotation on individual component classes


 Activating specific profiles by name
 • e.g. through a system property
   • -Dspring.profiles.active=development
 • or other means outside of the deployment unit
   • according to environment conventions


 Ideally: no need to touch deployment unit across different
 stages/environments



                                            CONFIDENTIAL       17
Java-Based Application Configuration
@FeatureConfiguration
@Import(DataConfig.class)
public class TxFeatures {
        @Feature
        public TxAnnotationDriven tx(DataConfig dataConfig) {
                 return new TxAnnotationDriven(dataConfig.txManager()).proxyTargetClass(true);
        }
}
                                                       <tx:annotation-driven transaction-manager="txManager"
                                                                  proxy-target-class="true"/>
@Configuration
public class DataConfig {
        @Bean
        public PlatformTransactionManager txManager() {
                 return new DataSourceTransactionManager(dataSource());
        }


        @Bean
        public DataSource dataSource() {
                 // ... configure and return JDBC DataSource ...
        }
}




                                                CONFIDENTIAL                                                   18
"c:" Namespace for XML Configuration
 New XML namespace for use with bean configuration
 • shortcut for <constructor-arg>
   • inline argument values
   • analogous to existing "p:" namespace
 • use of constructor argument names
   • recommended for readability
   • debug symbols have to be available in the application's class files


 <bean class="…" c:age="10" c:name="myName"/>


 <bean class="…" c:name-ref="nameBean"
     c:spouse-ref="spouseBean"/>




                                           CONFIDENTIAL                    19
Declarative Caching
@Cacheable

public Owner loadOwner(int id);



@Cacheable(condition="name.length < 10")

public Owner loadOwner(String name);



@CacheEvict

public void deleteOwner(int id);




                                   CONFIDENTIAL   20
Summary
 Spring 3 provides plenty of features for modern component design
 • focus on annotation-based components
 • also investing into concise XML-based bean definitions


 Selected core Spring 3.0 features
 • stereotypes, factory methods, EL
 • support for standardized annotations
 • declarative validation and formatting


 Selected enhancements in Spring 3.1
 • environment profiles for bean definitions
 • Java-based application configuration
 • declarative caching


                                       CONFIDENTIAL                  21
杭州站 · 2011年10月20日~22日
 www.qconhangzhou.com(6月启动)




QCon北京站官方网站和资料下载
     www.qconbeijing.com

More Related Content

What's hot

Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
srmelody
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10min
Corneil du Plessis
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
Carol McDonald
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 

What's hot (18)

Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
 
Spring 4 final xtr_presentation
Spring 4 final xtr_presentationSpring 4 final xtr_presentation
Spring 4 final xtr_presentation
 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10min
 
AAI 1713-Introduction to Java EE 7
AAI 1713-Introduction to Java EE 7AAI 1713-Introduction to Java EE 7
AAI 1713-Introduction to Java EE 7
 
Spring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web Views
 
Types of Dependency Injection in Spring
Types of Dependency Injection in SpringTypes of Dependency Injection in Spring
Types of Dependency Injection in Spring
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
 
Spring
SpringSpring
Spring
 
Java Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet BasicJava Web Programming [2/9] : Servlet Basic
Java Web Programming [2/9] : Servlet Basic
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
 
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 Basics
 
Struts course material
Struts course materialStruts course material
Struts course material
 

Similar to Spring design-juergen-qcon

Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
Gunith Devasurendra
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
Michał Orman
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
Guo Albert
 

Similar to Spring design-juergen-qcon (20)

Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
 
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdfdokumen.tips_rediscovering-spring-with-spring-boot1.pdf
dokumen.tips_rediscovering-spring-with-spring-boot1.pdf
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011
 
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam BrannenSpring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
 
Spring Framework Petclinic sample application
Spring Framework Petclinic sample applicationSpring Framework Petclinic sample application
Spring Framework Petclinic sample application
 
AAI-1713 Introduction to Java EE 7
AAI-1713 Introduction to Java EE 7AAI-1713 Introduction to Java EE 7
AAI-1713 Introduction to Java EE 7
 
Spring 3.1 in a Nutshell
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a Nutshell
 
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)InterConnect 2016 Java EE 7 Overview (PEJ-5296)
InterConnect 2016 Java EE 7 Overview (PEJ-5296)
 
Spring5 New Features
Spring5 New FeaturesSpring5 New Features
Spring5 New Features
 
Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4Spring review_for Semester II of Year 4
Spring review_for Semester II of Year 4
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 

More from Yiwei Ma

Cibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qconCibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qcon
Yiwei Ma
 
Cibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qconCibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qcon
Yiwei Ma
 
Taobao casestudy-yufeng-qcon
Taobao casestudy-yufeng-qconTaobao casestudy-yufeng-qcon
Taobao casestudy-yufeng-qcon
Yiwei Ma
 
Alibaba server-zhangxuseng-qcon
Alibaba server-zhangxuseng-qconAlibaba server-zhangxuseng-qcon
Alibaba server-zhangxuseng-qcon
Yiwei Ma
 
Zhongxing practice-suchunshan-qcon
Zhongxing practice-suchunshan-qconZhongxing practice-suchunshan-qcon
Zhongxing practice-suchunshan-qcon
Yiwei Ma
 
Taobao practice-liyu-qcon
Taobao practice-liyu-qconTaobao practice-liyu-qcon
Taobao practice-liyu-qcon
Yiwei Ma
 
Thoughtworks practice-hukai-qcon
Thoughtworks practice-hukai-qconThoughtworks practice-hukai-qcon
Thoughtworks practice-hukai-qcon
Yiwei Ma
 
Ufida design-chijianqiang-qcon
Ufida design-chijianqiang-qconUfida design-chijianqiang-qcon
Ufida design-chijianqiang-qcon
Yiwei Ma
 
Netflix web-adrian-qcon
Netflix web-adrian-qconNetflix web-adrian-qcon
Netflix web-adrian-qcon
Yiwei Ma
 
Google arch-fangkun-qcon
Google arch-fangkun-qconGoogle arch-fangkun-qcon
Google arch-fangkun-qcon
Yiwei Ma
 
Cibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qconCibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qcon
Yiwei Ma
 
Alibaba arch-jiangtao-qcon
Alibaba arch-jiangtao-qconAlibaba arch-jiangtao-qcon
Alibaba arch-jiangtao-qcon
Yiwei Ma
 
Twitter keynote-evan-qcon
Twitter keynote-evan-qconTwitter keynote-evan-qcon
Twitter keynote-evan-qcon
Yiwei Ma
 
Netflix keynote-adrian-qcon
Netflix keynote-adrian-qconNetflix keynote-adrian-qcon
Netflix keynote-adrian-qcon
Yiwei Ma
 
Facebook keynote-nicolas-qcon
Facebook keynote-nicolas-qconFacebook keynote-nicolas-qcon
Facebook keynote-nicolas-qcon
Yiwei Ma
 
Domainlang keynote-eric-qcon
Domainlang keynote-eric-qconDomainlang keynote-eric-qcon
Domainlang keynote-eric-qcon
Yiwei Ma
 
Devjam keynote-david-qcon
Devjam keynote-david-qconDevjam keynote-david-qcon
Devjam keynote-david-qcon
Yiwei Ma
 
Baidu keynote-wubo-qcon
Baidu keynote-wubo-qconBaidu keynote-wubo-qcon
Baidu keynote-wubo-qcon
Yiwei Ma
 
淘宝线上线下性能跟踪体系和容量规划-Qcon2011
淘宝线上线下性能跟踪体系和容量规划-Qcon2011淘宝线上线下性能跟踪体系和容量规划-Qcon2011
淘宝线上线下性能跟踪体系和容量规划-Qcon2011
Yiwei Ma
 
网游服务器性能优化-Qcon2011
网游服务器性能优化-Qcon2011网游服务器性能优化-Qcon2011
网游服务器性能优化-Qcon2011
Yiwei Ma
 

More from Yiwei Ma (20)

Cibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qconCibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qcon
 
Cibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qconCibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qcon
 
Taobao casestudy-yufeng-qcon
Taobao casestudy-yufeng-qconTaobao casestudy-yufeng-qcon
Taobao casestudy-yufeng-qcon
 
Alibaba server-zhangxuseng-qcon
Alibaba server-zhangxuseng-qconAlibaba server-zhangxuseng-qcon
Alibaba server-zhangxuseng-qcon
 
Zhongxing practice-suchunshan-qcon
Zhongxing practice-suchunshan-qconZhongxing practice-suchunshan-qcon
Zhongxing practice-suchunshan-qcon
 
Taobao practice-liyu-qcon
Taobao practice-liyu-qconTaobao practice-liyu-qcon
Taobao practice-liyu-qcon
 
Thoughtworks practice-hukai-qcon
Thoughtworks practice-hukai-qconThoughtworks practice-hukai-qcon
Thoughtworks practice-hukai-qcon
 
Ufida design-chijianqiang-qcon
Ufida design-chijianqiang-qconUfida design-chijianqiang-qcon
Ufida design-chijianqiang-qcon
 
Netflix web-adrian-qcon
Netflix web-adrian-qconNetflix web-adrian-qcon
Netflix web-adrian-qcon
 
Google arch-fangkun-qcon
Google arch-fangkun-qconGoogle arch-fangkun-qcon
Google arch-fangkun-qcon
 
Cibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qconCibank arch-zhouweiran-qcon
Cibank arch-zhouweiran-qcon
 
Alibaba arch-jiangtao-qcon
Alibaba arch-jiangtao-qconAlibaba arch-jiangtao-qcon
Alibaba arch-jiangtao-qcon
 
Twitter keynote-evan-qcon
Twitter keynote-evan-qconTwitter keynote-evan-qcon
Twitter keynote-evan-qcon
 
Netflix keynote-adrian-qcon
Netflix keynote-adrian-qconNetflix keynote-adrian-qcon
Netflix keynote-adrian-qcon
 
Facebook keynote-nicolas-qcon
Facebook keynote-nicolas-qconFacebook keynote-nicolas-qcon
Facebook keynote-nicolas-qcon
 
Domainlang keynote-eric-qcon
Domainlang keynote-eric-qconDomainlang keynote-eric-qcon
Domainlang keynote-eric-qcon
 
Devjam keynote-david-qcon
Devjam keynote-david-qconDevjam keynote-david-qcon
Devjam keynote-david-qcon
 
Baidu keynote-wubo-qcon
Baidu keynote-wubo-qconBaidu keynote-wubo-qcon
Baidu keynote-wubo-qcon
 
淘宝线上线下性能跟踪体系和容量规划-Qcon2011
淘宝线上线下性能跟踪体系和容量规划-Qcon2011淘宝线上线下性能跟踪体系和容量规划-Qcon2011
淘宝线上线下性能跟踪体系和容量规划-Qcon2011
 
网游服务器性能优化-Qcon2011
网游服务器性能优化-Qcon2011网游服务器性能优化-Qcon2011
网游服务器性能优化-Qcon2011
 

Spring design-juergen-qcon

  • 1. Modern Component Design with Spring 3 Jürgen Höller, Principal Engineer, SpringSource CONFIDENTIAL © 2010 SpringSource, A division of VMware. All rights reserved
  • 2. Spring 3.0 – Component Model Revisited  Powerful annotated component model • stereotypes, factory methods, JSR-330  Spring Expression Language • Unified EL++  Comprehensive REST support • and other Spring @MVC additions  Support for Portlet 2.0 request types • action/render/event/resource mappings  Declarative validation and formatting • integration with JSR-303 Bean Validation  Scheduling enhancements • scheduling annotation with cron support CONFIDENTIAL 2
  • 3. Enhanced Stereotype Model  Powerful options for custom annotations • combining meta-annotations e.g. on stereotype • automatically detected (no configuration necessary!) @Service @Scope("request") @Transactional(rollbackFor=Exception.class) @Retention(RetentionPolicy.RUNTIME) public @interface MyService {} @MyService public class BookAdminService { … } CONFIDENTIAL 3
  • 4. Annotated Factory Methods  Spring 3.0 includes the core functionality of the former Spring JavaConfig project • configuration classes defining managed beans • common handling of annotated factory methods @Bean @Primary @Lazy public BookAdminService bookAdminService() { MyBookAdminService service = new MyBookAdminService(); service.setDataSource(…); return service; } CONFIDENTIAL 4
  • 5. Standardized Annotations @ManagedBean public class MyBookAdminService implements BookAdminService { @Inject public MyBookAdminService(AccountRepository ar) { … } @TransactionAttribute public BookUpdate updateBook(Addendum addendum) { … } } CONFIDENTIAL 5
  • 6. JSR-330 and Co  @javax.inject.Inject is part of JSR-330 • "Dependency Injection for Java" • also defines @Qualifier semantics • and a Provider interface  @javax.annotation.ManagedBean is part of JSR-250 v1.1 • driven by the Java EE 6 specification • can be detected through classpath scanning  @javax.ejb.TransactionAttribute is part of the EJB 3.0/3.1 specification • also supported for Spring beans CONFIDENTIAL 6
  • 7. EL in XML Bean Definitions <bean class="mycompany.BookTestDatabase"> <property name="databaseName" value="#{systemProperties.databaseName}"/> <property name="keyGenerator" value="#{strategyBean.databaseKeyGenerator}"/> </bean> CONFIDENTIAL 7
  • 8. EL in Component Annotations @Repository public class BookTestDatabase { @Value("#{systemProperties.databaseName}") public void setDatabaseName(String dbName) { … } @Value("#{strategyBean.databaseKeyGenerator}") public void setKeyGenerator(KeyGenerator kg) { … } } CONFIDENTIAL 8
  • 9. REST in MVC - @PathVariable http://mybookstore.com/books/12345 @RequestMapping(value = "/books/{id}", method = GET) public Book findBook(@PathVariable("id") long id) { return this.bookAdminService.findBook(id); } CONFIDENTIAL 9
  • 10. Portlet 2.0 Support in MVC @Controller @RequestMapping("EDIT") public class MyPortletController { @ActionMapping("delete") public void removeBook(@RequestParam("book") String bookId) { this.myService.deleteBook(bookId); } @EventMapping("BookUpdate") public void updateBook(BookUpdateEvent bookUpdate) { // extract book entity data from event payload object this.myService.updateBook(…); } } CONFIDENTIAL 10
  • 11. Declarative Model Validation public class Book { @NotNull @Past private Date releaseDate; } @RequestMapping("/books/new") public void newBook(@Valid Book book) { … }  JSR-303 "Bean Validation" as the common ground  Spring 3.0 fully supports JSR-303 for MVC data binding  Same metadata can be used for persisting, rendering, etc CONFIDENTIAL 11
  • 12. Conversion and Formatting  Spring 3.0 features a revised binding and type conversion infrastructure • stateless Java 5+ type converters and formatters • annotation-driven number/date formatting public class Book { @NotNull @Past @DateTimeFormat(iso=ISO.DATE) private Date releaseDate; } CONFIDENTIAL 12
  • 13. Scheduling Enhancements  Spring 3.0 introduces a major overhaul of the scheduling package • TaskScheduler interface with Trigger abstraction • XML scheduling namespace with cron support • @Async annotation for asynchronous user methods • @Scheduled annotation for cron-triggered methods @Scheduled(cron = "0 0 12 * * ?") public void performTempFileCleanup() { ... } CONFIDENTIAL 13
  • 14. Related Java EE 6 Specifications  Java EE 6 API support in Spring Framework 3.0 • several specifications adopted into the Spring component model  Integration with JPA 2.0 • support for query builder, native delegates, etc  Integration with JSF 2.0 • full compatibility as a managed bean facility  JSR-303 Bean Validation integration • through Hibernate Validator 4.1  JSR-330: common dependency injection annotations • natively supported by Spring itself CONFIDENTIAL 14
  • 15. Spring 3.1 – Component Model Enhancements  Environment profiles for bean definitions  Java-based application configuration  "c:" namespace for XML configuration  Declarative caching CONFIDENTIAL 15
  • 16. Environment Profiles <beans profile="production"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClass" value="${database.driver}"/> <property name="jdbcUrl" value="${database.url}"/> <property name="username" value="${database.username}"/> <property name="password" value="${database.password}"/> </bean> </beans> <beans profile="embedded"> <jdbc:embedded-database id="dataSource" type="H2"> <jdbc:script location="/WEB-INF/database/schema-member.sql"/> <jdbc:script location="/WEB-INF/database/schema-activity.sql"/> <jdbc:script location="/WEB-INF/database/schema-event.sql"/> <jdbc:script location="/WEB-INF/database/data.sql"/> </jdbc:embedded-database> </beans> CONFIDENTIAL 16
  • 17. Environment Configuration  Environment association of specific bean definitions • XML 'profile' attribute on <beans> element • @Profile annotation on configuration classes • @Profile annotation on individual component classes  Activating specific profiles by name • e.g. through a system property • -Dspring.profiles.active=development • or other means outside of the deployment unit • according to environment conventions  Ideally: no need to touch deployment unit across different stages/environments CONFIDENTIAL 17
  • 18. Java-Based Application Configuration @FeatureConfiguration @Import(DataConfig.class) public class TxFeatures { @Feature public TxAnnotationDriven tx(DataConfig dataConfig) { return new TxAnnotationDriven(dataConfig.txManager()).proxyTargetClass(true); } } <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/> @Configuration public class DataConfig { @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManager(dataSource()); } @Bean public DataSource dataSource() { // ... configure and return JDBC DataSource ... } } CONFIDENTIAL 18
  • 19. "c:" Namespace for XML Configuration  New XML namespace for use with bean configuration • shortcut for <constructor-arg> • inline argument values • analogous to existing "p:" namespace • use of constructor argument names • recommended for readability • debug symbols have to be available in the application's class files <bean class="…" c:age="10" c:name="myName"/> <bean class="…" c:name-ref="nameBean" c:spouse-ref="spouseBean"/> CONFIDENTIAL 19
  • 20. Declarative Caching @Cacheable public Owner loadOwner(int id); @Cacheable(condition="name.length < 10") public Owner loadOwner(String name); @CacheEvict public void deleteOwner(int id); CONFIDENTIAL 20
  • 21. Summary  Spring 3 provides plenty of features for modern component design • focus on annotation-based components • also investing into concise XML-based bean definitions  Selected core Spring 3.0 features • stereotypes, factory methods, EL • support for standardized annotations • declarative validation and formatting  Selected enhancements in Spring 3.1 • environment profiles for bean definitions • Java-based application configuration • declarative caching CONFIDENTIAL 21
  • 22. 杭州站 · 2011年10月20日~22日 www.qconhangzhou.com(6月启动) QCon北京站官方网站和资料下载 www.qconbeijing.com