A Walking Tour of Spring 3.1Josh Long, Spring Developer Advocate, SpringSourceJürgen Höller, Principal Engineer, SpringSou...
About Josh LongSpring Developer Advocatetwitter: @starbuxmanjosh.long@springsource.com                             NOT CON...
Deployment Platforms: Becoming More Diverse        Application   Application      Application       Frameworks     Framewo...
Wide Variety of Data and Datastores Not all data resides in relational databases            cloud environments often sug...
Wide Variety of Web Clients More and more client-side web technologies            HTML 5 as a next-generation browser st...
Key Elements of Spring: Ready for 2012 & Beyond                 on              cti                e            Inj       ...
Whats New? Spring Framework 3.1 Spring Integration 2.1 Spring Data 1.0 Spring Security 3.1                           7
Spring Framework 3.1: Selected Features Environment abstraction and profiles Java-based application configuration Overh...
Environment Abstraction Grouping bean definitions for activation in specific environments • e.g. development, testing, pr...
Bean Definition Profiles<beans profile="production">  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource...
Environment Configuration Associating specific bean definitions with specific environments • XML profile attribute on <be...
Java-Based Application Configuration Application-specific container configuration • aligned with Spring 3.0s @Configurati...
Application Configuration Example@Configuration@EnableTransactionManagement(proxyTargetClass=true)       <tx:annotation-dr...
Test Context Framework@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(    loader=AnnotationConfigContextLoade...
Interlude: "c:" Namespace New XML namespace for use with bean configuration • shortcut for <constructor-arg>   • inline a...
Cache Abstraction CacheManager and Cache abstraction • in org.springframework.cache   • which up until 3.0 just contained...
Declarative Caching@Cacheablepublic Owner loadOwner(int id);@Cacheable(condition="name.length < 10")public Owner loadOwner...
Servlet 3.0 Based Web Applications Explicit support for Servlet 3.0 containers • such as Tomcat 7 and GlassFish 3 • while...
WebApplicationInitializer Example/** * Automatically detected and invoked on startup by Springs   ServletContainerInitiali...
@MVC Processing & Flash Attributes RequestMethodHandlerAdapter          arbitrary mappings to handler methods across mul...
Refined JPA Support Package scanning without persistence.xml            packagesToScan feature on LocalContainerEntityMa...
Third-Party Support Updates Hibernate 4.0            natively and through JPA            native support in a dedicated ...
Java SE 7 Spring 3.1 introduces Java SE 7 support            making best use of JRE 7 at runtime            support for...
Summary Spring serves as an enabler for modern Java architectures            annotated components with dependency inject...
Spring Integration 2.1 JSR-223 Scripting Support (Javascript, JRuby, Jython, Groovy) AMQP/RabbitMQ Spring Data:       ...
Stored Procedures inbound/outbound Channel Adapters outbound Gateway supports stored procs on: derby, db2, mysql, ms sq...
Payload EnricherForward message to a nested flow and evaluate an expression against the result to enrich the payload    <i...
FTP and SFTPAdding request/reply functionality in addition to the existing one-way Channel Adapters     <int-ftp:outbound-...
Spring Data: Background and Motivation   Data access landscape has changed considerably   RDBMS are still important and ...
Spring Data is an “umbrella project”   JPA -   JDBC Extensions   Hadoop – Big Data Storage and Analysis platform   Gem...
Spring Data Repositoriesp u b l i c i n t e r f a c e R e p o s i t o r y <T , I D e x t e n d s S e r i a l i z a b l e >...
Spring Data Repositoriesp u b l i c i n t e r f a c e R e p o s i t o r y <T , I D e x t e n d s S e r i a l i z a b l e >...
Spring Security 3.1   Multiple http elements   Stateless authentication   Improved Active Directory LDAP support   Cry...
Spring Security: Project Organization        Luke Taylor (VMW),        Rob Winch                                          ...
github.com/joshlong/a-walking-tour-of-spring-31/                Questions?               Say hi on Twitter:          @star...
Upcoming SlideShare
Loading in …5
×

Spring 3.1: a Walking Tour

3,525 views

Published on

This talk introduces how to build applications using some of the features in Spring 3.1, the new framework from SpringSource, a division of VMWare

Published in: Technology, Education
0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
3,525
On SlideShare
0
From Embeds
0
Number of Embeds
39
Actions
Shares
0
Downloads
97
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide
  • Hello, thank you or having me. Im pleased to have the opportunity to introduce you today to Spring and the SpringSource Tool Suite My anem is Josh Long. I serve as the developer advocate for the Spring framework. I’ve used it in earnest and advocated it for many years now. i’m an author on 3 books on the technology, as well as a comitter to many of the Spring projects. Additionally, I take community activism very seriously and do my best to participate in the community. Sometimes this means answering question on Twitter, or in the forums, or helping contribute to the InfoQ.com and Artima.com communities
  • Spring 3.1: a Walking Tour

    1. 1. A Walking Tour of Spring 3.1Josh Long, Spring Developer Advocate, SpringSourceJürgen Höller, Principal Engineer, SpringSourceMark Fisher, Senior Staff Engineer, SpringSourceMark Pollack, Senior Staff Engineer, SpringSourceDave Syer, Senior Staff Engineer, SpringSource © 2012 SpringSource, A division of VMware. All rights reserved
    2. 2. About Josh LongSpring Developer Advocatetwitter: @starbuxmanjosh.long@springsource.com NOT CONFIDENTIAL -- TELL EVERYONE 2
    3. 3. Deployment Platforms: Becoming More Diverse Application Application Application Frameworks Frameworks Frameworks + Libraries + Libraries + Libraries WebSphere Tomcat Cloud Platform 3
    4. 4. Wide Variety of Data and Datastores Not all data resides in relational databases  cloud environments often suggest alternatives for scalability reasons  HBase, Redis, Mongo, etc Distributed caches add challenges as well  not least of it all in terms of application-level access patterns  GemFire, Coherence, etc Hardly any standardization available  JSR-107 – for caching – did not make progress for a long, long time  finally getting picked up in Java EE 7, but again only for caching  alternative datastore space is too diverse for standardization 4
    5. 5. Wide Variety of Web Clients More and more client-side web technologies  HTML 5 as a next-generation browser standard  Adobe Flex as a rich client technology on the basis of Flash Server-side state to be minimized or even removed completely  in particular: no server-side user interface state  strictly controlled user session state JSFs state-centric approach not a great fit anymore  except for special kinds of applications (which it remains very useful for)  web application backends and web services based on JAX-RS / MVC style  nevertheless: JSF keeps evolving – JSF 2.2 coming up in 2012 5
    6. 6. Key Elements of Spring: Ready for 2012 & Beyond on cti e Inj AO cy P en nd pe De Simple Simple Objects Portable Service Abstractions Object More important than ever! 6
    7. 7. Whats New? Spring Framework 3.1 Spring Integration 2.1 Spring Data 1.0 Spring Security 3.1 7
    8. 8. Spring Framework 3.1: Selected Features Environment abstraction and profiles Java-based application configuration Overhaul of the test context framework Cache abstraction & declarative caching Servlet 3.0 based web applications @MVC processing & flash attributes Refined JPA support Hibernate 4.0 & Quartz 2.0 Support for Java SE 7 8
    9. 9. Environment Abstraction Grouping bean definitions for activation in specific environments • e.g. development, testing, production • possibly different deployment environments Custom resolution of placeholders • dependent on the actual environment • hierarchy of property sources Injectable environment abstraction API • org.springframework.core.env.Environment Unified property resolution SPI • org.springframework.core.env.PropertyResolver 9
    10. 10. Bean Definition 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> 10
    11. 11. Environment Configuration Associating specific bean definitions with specific environments • 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 11
    12. 12. Java-Based Application Configuration Application-specific container configuration • aligned with Spring 3.0s @Configuration style • focus on customizing the annotation-based processing parts of Spring Equivalent to XML namespace functionality • but not a one-to-one mapping • natural container configuration from an annotation-oriented perspective Typical infrastructure setup • transactions • scheduling • MVC customization 12
    13. 13. Application Configuration Example@Configuration@EnableTransactionManagement(proxyTargetClass=true) <tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>public class DataConfig { @Bean public PlatformTransactionManager txManager() { return new HibernateTransactionManager(sessionFactory()); } @Bean public SessionFactory sessionFactory() throws Exception { return new LocalSessionFactoryBuilder(dataSource()) .addAnnotatedClasses(Order.class, Account.class) .buildSessionFactory(); } @Bean public DataSource dataSource() { // ... configure and return JDBC DataSource ... }} 13
    14. 14. Test Context Framework@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes={TransferServiceConfig.class, DataConfig.class})@ActiveProfiles("dev")public class TransferServiceTest { @Autowired private TransferService transferService; @Test public void testTransferService() { ... }} 14
    15. 15. Interlude: "c:" Namespace 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 applications class files <bean class="…" c:age="10" c:name="myName"/> <bean class="…" c:name-ref="nameBean" c:spouse-ref="spouseBean"/> 15
    16. 16. Cache Abstraction CacheManager and Cache abstraction • in org.springframework.cache • which up until 3.0 just contained EhCache support • particularly important with the rise of distributed caching • not least of it all: in cloud environments Backend adapters for EhCache, GemFire, Coherence, etc • EhCache adapter shipping with Spring core • JSR-107 a.k.a. JCache support coming in Spring 3.2 Specific cache setup per environment – through profiles? • potentially even adapting to a runtime-provided service 16
    17. 17. Declarative Caching@Cacheablepublic Owner loadOwner(int id);@Cacheable(condition="name.length < 10")public Owner loadOwner(String name);@CacheEvictpublic void deleteOwner(int id); 17
    18. 18. Servlet 3.0 Based Web Applications Explicit support for Servlet 3.0 containers • such as Tomcat 7 and GlassFish 3 • while at the same time preserving compatibility with Servlet 2.4+ Support for XML-free web application setup (no web.xml) • Servlet 3.0s ServletContainerInitializer mechanism • in combination with Spring 3.1s AnnotationConfigWebApplicationContext • plus Spring 3.1s environment abstraction Exposure of native Servlet 3.0 functionality in Spring MVC • standard Servlet 3.0 file upload behind Springs MultipartResolver abstraction • support for asynchronous request processing coming in Spring 3.2 18
    19. 19. WebApplicationInitializer Example/** * Automatically detected and invoked on startup by Springs ServletContainerInitializer. May register listeners, filters, servlets etc against the given Servlet 3.0 ServletContext. */public class MyWebAppInitializer implements WebApplicationInitializer { public void onStartup(ServletContext sc) throws ServletException { // Create the root Spring application context AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); root.scan("com.mycompany.myapp"); root.register(FurtherConfig.class); // Manages the lifecycle of the root application context sc.addListener(new ContextLoaderListener(root)); ... }} 19
    20. 20. @MVC Processing & Flash Attributes RequestMethodHandlerAdapter  arbitrary mappings to handler methods across multiple controllers  better customization of handler method arguments HandlerMethodArgumentResolver HandlerMethodReturnValueHandler etc FlashMap support and FlashMapManager abstraction  with RedirectAttributes as a new @MVC handler method argument type explicitly calling addFlashAttribute to add values to the output FlashMap  an outgoing FlashMap will temporarily get added to the users session  an incoming FlashMap for a request will automatically get exposed to the model 20
    21. 21. Refined JPA Support Package scanning without persistence.xml  packagesToScan feature on LocalContainerEntityManagerFactoryBean building a persistence unit from @Entity classes within specific application packages  similar to AnnotationSessionFactoryBean for Hibernate 3 rolled into core LocalSessionFactoryBean for Hibernate 4  ideal for applications with a single default persistence unit Consistent JPA setup by persistence unit name  JPA specification quite strongly based on the notion of persistence unit names @PersistenceContext / @PersistenceUnit referring to persistence unit names  now Springs JpaTransactionManager and co support setup by unit name as well as an alternative to referring to EntityManagerFactory beans directly 21
    22. 22. Third-Party Support Updates Hibernate 4.0  natively and through JPA  native support in a dedicated org.springframework.orm.hibernate4 package dealing with package rearrangements in the Hibernate API  preserving compatibility with Hibernate 3.2+ in orm.hibernate3 Quartz 2.0  JobDetail and Trigger are now interfaces in the Quartz 2.0 API whereas they traditionally were base classes in Quartz 1.x  SchedulerFactoryBean now auto-adapts to Quartz 2.0 if present JobDetail/CronTrigger/SimpleTriggerFactoryBean variants for Quartz 2.0  preserving compatibility with Quartz 1.5+ in the same support package 22
    23. 23. Java SE 7 Spring 3.1 introduces Java SE 7 support  making best use of JRE 7 at runtime  support for JDBC 4.1  support for fork-join framework Oracles OpenJDK 7 released in summer 2011  IBM JDK 7 following not much later  Java 7 could be the norm for new Java based projects soon Spring Framework not being built against Java 7 yet  build upgrade coming in Spring 3.2 23
    24. 24. Summary Spring serves as an enabler for modern Java architectures  annotated components with dependency injection and declarative services  flexible deployment options for any Java based target platform Java SE 7 and Servlet 3.0 as common ground for years to come  embedded application frameworks such as Spring are a perfect fit on top  Spring as a programming and configuration model for cloud-based deployments Spring Framework 3.1 introduces several new key features  environment abstraction and bean definition profiles  cache abstraction and declarative caching  web application deployment without web.xml  compatibility with the latest platform standards and libraries 24
    25. 25. Spring Integration 2.1 JSR-223 Scripting Support (Javascript, JRuby, Jython, Groovy) AMQP/RabbitMQ Spring Data:  GemFire  Redis  MongoDB Stored Procedures Resource Inbound Channel Adapter XPath Filter Payload Enricher FTP and SFTP Outbound Gateways STS Templates 25
    26. 26. Stored Procedures inbound/outbound Channel Adapters outbound Gateway supports stored procs on: derby, db2, mysql, ms sql, oracle, postgres, sybase supports sql functions on: mysql, ms sql, oracle, postgres 26
    27. 27. Payload EnricherForward message to a nested flow and evaluate an expression against the result to enrich the payload <int:enricher id="findUserByUsernameEnricher" input-channel="findUserByUsernameEnricherChannel" request-channel="findUserByUsernameServiceChannel" request-payload-expression="payload.username"> <int:property name="email" expression="payload.email"/> <int:property name="password" expression="payload.password"/> </int:enricher> 27
    28. 28. FTP and SFTPAdding request/reply functionality in addition to the existing one-way Channel Adapters <int-ftp:outbound-gateway id="gatewayGET" cache-sessions="false" local-directory="/tmp/gatewayGET" session-factory="ftpSessionFactory" request-channel="toGet" reply-channel="toRemoveChannel" command="get" command-options="-P" expression="payload.remoteDirectory + / + payload.filename"/> 28
    29. 29. Spring Data: Background and Motivation Data access landscape has changed considerably RDBMS are still important and predominant• but no longer considered a “one size fits all” solution Spring has always provided excellent data access support Spring Data project goal is to “refresh” Spring’s data support for• Traditional: JDBC, JPA• New: Grid, NoSql, Hadoop Provide familiar and consistent Spring-based programming model• While retaining technology specific features and capabilities Remove boiler-plate code for writing a data access layer• Common interfaces that can be used across different technologies
    30. 30. Spring Data is an “umbrella project” JPA - JDBC Extensions Hadoop – Big Data Storage and Analysis platform Gemfire – Distributed Data Grid Redis – Key Value Database MongoDB – Document Database Neo4j – Graph Database Commons – shared abstractions• Repositories• Object Mapping QueryDSL – integration with type-safe query API
    31. 31. Spring Data Repositoriesp u b l i c i n t e r f a c e R e p o s i t o r y <T , I D e x t e n d s S e r i a l i z a b l e > {}p u b l i c i n t e r f a c e C r u d R e p o s i t o r y <T , I D e x t e n d s S e r i a l i z a b l e > e x t e n d s R e p o s i t o r y <T , I D > { T s a v e ( T e n t it y ) ; I t e r a b l e <T > s a v e ( I t e r a b l e <? e x t e n d s T > e n t i t i e s ) ; T f in d O n e ( ID id ) ; b o o le a n e x is t s ( ID id ) ; I t e r a b l e <T > f i n d A l l ( ) ; lo n g c o u n t ( ) ; v o id d e le t e ( ID id ) ; v o id d e le t e ( T e n t it y ) ; v o i d d e l e t e ( I t e r a b l e <? e x t e n d s T > e n t i t i e s ) ; v o id d e le t e A ll( ) ;}
    32. 32. Spring Data Repositoriesp u b l i c i n t e r f a c e R e p o s i t o r y <T , I D e x t e n d s S e r i a l i z a b l e > {}p u b l i c i n t e r f a c e C r u d R e p o s i t o r y <T , I D e x t e n d s S e r i a l i z a b l e > e x t e n d s R e p o s i t o r y <T , I D > { T s a v e ( T e n t it y ) ; I t e r a b l e <T > s a v e ( I t e r a b l e <? e x t e n d s T > e n t i t i e s ) ; T f in d O n e ( ID id ) ; b o o le a n e x is t s ( ID id ) ; I t e r a b l e <T > f i n d A l l ( ) ; lo n g c o u n t ( ) ; v o id d e le t e ( ID id ) ; v o id d e le t e ( T e n t it y ) ; v o i d d e l e t e ( I t e r a b l e <? e x t e n d s T > e n t i t i e s ) ; v o id d e le t e A ll( ) ;}
    33. 33. Spring Security 3.1 Multiple http elements Stateless authentication Improved Active Directory LDAP support Crypto Module. Disabling UI security (for testing purposes) Erasing credentials after successful authentication Clearing cookies on logout Support arbitrary implementations of JAAS Configuration 33
    34. 34. Spring Security: Project Organization Luke Taylor (VMW), Rob Winch Core Spring Security Web  3.1.0 released  Stable, matureRyan Heaton, ...Dave Syer (VMW), LDAP OpenID Spring Security OAuth Spring Extensions: Security Vladimir Schaefer, Keith Donald, Mike Wiesner (VMW) OAuth2 Craig Walls (VMW) OAuth1a SAML Kerberos Spring Social  Oauth2 spec not yet final  External lead  1.0.0 not yet released  1.0.0 released  Partly external, low-activity  1.0.0.M6 release in pipeline  Consumer for well- known providers CONFIDENTIAL 34
    35. 35. github.com/joshlong/a-walking-tour-of-spring-31/ Questions? Say hi on Twitter: @starbuxman @springsource NOT CONFIDENTIAL -- TELL EVERYONE

    ×