22
© 2010 SpringSource, A division of VMware. All rights reserved CONFIDENTIAL © 2010 SpringSource, A division of VMware. All rights reserved CONFIDENTIAL Modern Component Design with Spring 3 Jürgen Höller, Principal Engineer, SpringSource

Spring design-juergen-qcon

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Spring design-juergen-qcon

© 2010 SpringSource, A division of VMware. All rights reserved

CONFIDENTIAL

© 2010 SpringSource, A division of VMware. All rights reserved

CONFIDENTIAL

Modern Component Design with Spring 3

Jürgen Höller, Principal Engineer, SpringSource

Page 2: Spring design-juergen-qcon

2CONFIDENTIAL 2CONFIDENTIAL

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

Page 3: Spring design-juergen-qcon

3CONFIDENTIAL 3CONFIDENTIAL

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 {}

@MyServicepublic class BookAdminService { …}

Page 4: Spring design-juergen-qcon

4CONFIDENTIAL 4CONFIDENTIAL

Annotated Factory Methods

Spring 3.0 includes the core functionality of the formerSpring JavaConfig project• configuration classes defining managed beans• common handling of annotated factory methods

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

Page 5: Spring design-juergen-qcon

5CONFIDENTIAL 5CONFIDENTIAL

Standardized Annotations

@ManagedBeanpublic class MyBookAdminService implements BookAdminService {

@Inject public MyBookAdminService(AccountRepository ar) { … }

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

Page 6: Spring design-juergen-qcon

6CONFIDENTIAL 6CONFIDENTIAL

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

Page 7: Spring design-juergen-qcon

7CONFIDENTIAL 7CONFIDENTIAL

EL in XML Bean Definitions

<bean class="mycompany.BookTestDatabase">

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

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

</bean>

Page 8: Spring design-juergen-qcon

8CONFIDENTIAL 8CONFIDENTIAL

EL in Component Annotations

@Repositorypublic class BookTestDatabase {

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

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

}

Page 9: Spring design-juergen-qcon

9CONFIDENTIAL 9CONFIDENTIAL

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

http://mybookstore.com/books/12345

REST in MVC - @PathVariable

Page 10: Spring design-juergen-qcon

10CONFIDENTIAL 10CONFIDENTIAL

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(…); }}

Page 11: Spring design-juergen-qcon

11CONFIDENTIAL 11CONFIDENTIAL

Declarative Model Validationpublic 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

Page 12: Spring design-juergen-qcon

12CONFIDENTIAL 12CONFIDENTIAL

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;}

Page 13: Spring design-juergen-qcon

13CONFIDENTIAL 13CONFIDENTIAL

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() { ...}

Page 14: Spring design-juergen-qcon

14CONFIDENTIAL 14CONFIDENTIAL

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

Page 15: Spring design-juergen-qcon

15CONFIDENTIAL 15CONFIDENTIAL

Spring 3.1 – Component Model Enhancements

Environment profiles for bean definitions Java-based application configuration "c:" namespace for XML configuration Declarative caching

Page 16: Spring design-juergen-qcon

16CONFIDENTIAL 16CONFIDENTIAL

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>

Page 17: Spring design-juergen-qcon

17CONFIDENTIAL 17CONFIDENTIAL

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

Page 18: Spring design-juergen-qcon

18CONFIDENTIAL 18CONFIDENTIAL

Java-Based Application Configuration@FeatureConfiguration@Import(DataConfig.class)public class TxFeatures { @Feature public TxAnnotationDriven tx(DataConfig dataConfig) { return new TxAnnotationDriven(dataConfig.txManager()).proxyTargetClass(true); }}

@Configurationpublic class DataConfig { @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManager(dataSource()); }

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

<tx:annotation-driven transaction-manager="txManager"proxy-target-class="true"/>

Page 19: Spring design-juergen-qcon

19CONFIDENTIAL 19CONFIDENTIAL

"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"/>

Page 20: Spring design-juergen-qcon

20CONFIDENTIAL 20CONFIDENTIAL

Declarative Caching@Cacheablepublic Owner loadOwner(int id);

@Cacheable(condition="name.length < 10")public Owner loadOwner(String name);

@CacheEvictpublic void deleteOwner(int id);

Page 21: Spring design-juergen-qcon

21CONFIDENTIAL 21CONFIDENTIAL

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

Page 22: Spring design-juergen-qcon

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

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