Upload
sam-brannen
View
6.695
Download
2
Tags:
Embed Size (px)
DESCRIPTION
As the leading full-stack application framework for Java SE and EE, the Spring Framework continues to deliver significant benefits to Java developers, increasing development productivity and runtime performance while improving test coverage and application quality. In this talk, core Spring Framework committer Sam Brannen will provide attendees an overview of the new features in Spring 3.2 as well as a sneak peak at the roadmap for 4.0. Spring Framework 3.2 builds on several themes delivered in 3.1 with a continued focus on asynchronous MVC processing with Servlet 3.0, support for using @Autowired and @Value as meta-annotations, support for custom @Bean definition annotations, and early support for JCache 0.5. Regarding the internals, CGLIB 3.0 and ASM 4.0 have been inlined, and the framework is now built with Gradle and hosted on GitHub. For those interested in testing their Spring-based web applications, Spring 3.2 offers new support for loading WebApplicationContexts in the TestContext framework, and the formerly standalone Spring MVC Test project is now included in the spring-test module, allowing for first-class testing of Spring MVC applications.
Citation preview
Spring Framework 3.2What’s New? What’s Coming?
Sam Brannen@sam_brannen
JUG.ch | Zurich | 22 January 2013
2
Sam Brannen
• Spring and Java Consultant @ Swiftmind
• Developing Java for over 15 years
• Spring Framework Core Committer since 2007
• Spring Trainer
• Lead author of Spring Distilled (O’Reilly)
• Presenter on Spring, Java, OSGi, and testing
3
Swiftmind
Your Experts for Enterprise Java
Experienced consultants with in-depth knowledge of:
– Spring– Java EE– OSGi– Agile project methodologies– Software engineering best practices
• Headquarters: Zurich, Switzerland
• http://www.swiftmind.com
4
A Show of Hands…
5
Agenda
• Major Themes in 3.2• Community and Contributions• Spring MVC Updates• Spring TestContext Framework Updates• Spring MVC Test Framework• 4.0 Roadmap• Q & A
6
Major Themes in 3.2
• Build system and source control changes
• Java 7 with inlined ASM 4.0 and CGLIB 3.0• Composable injection annotations• Early JCache (JSR-107) support
• Async MVC processing on Servlet 3.0• REST support refinements
• Testing web apps and Spring MVC Test Framework
• Several runtime and performance refinements
7
Java SE 7
• Spring 3.1 came with early support for Java 7– JDBC 4.1, ForkJoinPool, etc.– framework itself still compiled on Java 6
• Spring 3.2 is now being built on OpenJDK 7– with fine-tuning for Java 7 based tests, etc.– retaining compatibility with Java 5 & 6
8
ASM 4.0 & CGLIB 3.0
• Spring 3.2 comes with ASM 4.0 and CGLIB 3.0
– fully supporting the Java 7 byte code format
– ASM and CGLIB are now inlined into Spring module jars
9
Composable Injection Annotations
• Meta-annotations work for @Autowired, @Value, and @Bean as well
@Autowired @MyQualifier
@Retention(RetentionPolicy.RUNTIME)public @interface MyAutowired {}
@Value("#{systemProperties.myPort}")@Retention(RetentionPolicy.RUNTIME)public @interface MyPort {}
@Bean @MyQualifier @Lazy@Retention(RetentionPolicy.RUNTIME)public @interface MyBean {}
10
Early JCache Support
• Aligned with Spring's cache abstraction– Built against JCache 0.5 (JSR-107 draft)
• JCacheCacheManager and JCacheManagerFactoryBean– next to spiced-up versions of our
EhCacheCacheManager
• No out-of-the-box support for native JCache annotations yet– planned for 2013, once the JCache specification is final
11
Community and Contributions
12
Big Infrastructure Changes
• Moved Spring Framework sources from self-hosted Subversion to Git/GitHub
• Migrated from Spring Build (i.e., Ant + Ivy) to Gradle
• New SpringSource Artifactory repository– http://repo.springsource.org– https://github.com/SpringSource/spring-framework/wiki
/SpringSource-repository-FAQ
13
GitHub Repositories
14
GitHub – Timeline
• Dec 2011: Spring Framework moved to GitHub
• Dec 2012: 600+ forks; 200+ pull requests (thank you!)
15
Ways to Contribute (1/4)
• Answering questions on the Spring Forums and StackOverflow
– A great way to help others and build your own reputation
16
Spring on StackOverflow
17
Ways to Contribute (2/4)
• Submitting bug reports
– Because we can't fix what we don’t know is broken!
• Suggesting new features or improvements
18
Ways to Contribute (3/4)
• Trying out new features in snapshots, milestones, and release candidates
– Providing critical feedback for the team towards the next major version
19
Snapshot, Milestone, & RC Artifacts
20
Ways to Contribute (4/4)
• Contributing code
– To “scratch your own itch”
– To get (much!) more familiar with the framework
– To build your own reputation
21
Building from Source
Gradle build makes building from source dead simple
• git and JDK 7 are the only requirements
• clone the repo; run `./gradlew build`
• built-in scripts help with importing sources into Eclipse/STS or IDEA
• https://github.com/SpringSource/spring-framework/#building-from-source
22
Submitting Pull Requests
Pull Requests are a big help
• Much better than traditional patches
• https://github.com/SpringSource/springframework/blob/master/CONTRIBUTING.md
23
Reproducing Issues
New spring-framework-issues repository
• Submit “reproduction projects” that demonstrate JIRA issues
• See https://github.com/SpringSource/spring-framework-issues#readme
24
Contributions are Welcome!
• Interested in contributing?• Want to know which issues are best to work on?
• See the new Contributions Welcome fixVersion in SPR JIRA
• We’ll add issues here that we think are great candidates for community contribution
25
Contributions Welcome
26
Staying Informed
• Stay in touch with the team via Twitter– https://twitter.com/springframework– https://twitter.com/springframework/team/members
• Subscribe to the SpringSource Newsletter– http://www.springsource.org/newsletter-subscription
• Spring Framework Contributors Google Group– https://groups.google.com/forum/#!forum/spring-framework-
contrib
27
Spring MVC Updates
28
Servlet 3 Async Support
• What?– Separate processing from Servlet container thread
• How?– Start async processing via request.startAsync()– Exit container thread– Compute in another thread– Dispatch to container to complete processing
• Why?– Support for long running requests – e.g. long polling– Increased throughput
29
Spring MVC – Servlet 3 Async Support
New controller method return value types:
• java.util.Callable<?>– Actual return value to be obtained via Callable– Spring MVC invokes Callable in separate thread
• org.springframework.web.*.DeferredResult<?>– Actual return value to be set on the DeferredResult– Application sets DeferredResult from a thread of its
choice
30
java.util.Callable<?>
• Before:
• After:
• Do the same with any controller return value type– String, ModelAndView, ResponseEntity<?>, …
31
org.sfw.web.*.DeferredResult<?>
• Create and save a DeferredResult:
• Set the deferred result to complete processing:
32
Server-side Push via Long Polling
• Browser sends a request• Controller method returns a DeferredResult• Servlet container thread is exited but response is open• External event takes place – e.g. JMS, AMQP notification• DeferredResult is set• Request is dispatched back to Servlet container• Processing resumes and completes
See blog post on real-time update techniques:http://bit.ly/IWxRhI
33
Servlet 3 Async Configuration
• Set async-supported flag on Servlet and all filters– <async-supported>true</async-supported>
• Set <dispatcher> element on filter-mapping– <dispatcher>REQUEST, ASYNC, FORWARD</dispatcher>
34
Spring MVC Servlet 3 Async – Resources
• Blog post series– http://bit.ly/JIZwSV
• Samples– https://github.com/SpringSource/spring-mvc-showcase– https://github.com/rstoyanchev/spring-mvc-chat– http://bit.ly/VMLLuL … Spring AMQP stocks sample
• Reference documentation– http://bit.ly/UZzvsi
35
WebApplicationInitializer Base Classes
36
Content Negotiation Options
• Content negotiation via file extension, Accept header, request parameter, default value, or a custom strategy throughout Spring MVC
• Choose which strategies to use and in what order
• Configured once in MVC Java config or MVC namespace– “.json” and “.xml” extensions automatically enabled
• May configure HandlerMapping/Adapter and ExceptionResolver via ContentNegotiationManagerFactoryBean
For further details see: http://bit.ly/10cCcuG
37
Global Error Reporting
• Need an application–wide strategy for writing error details to the response body?
• Wishing there were a global @ExceptionHandler method?
• Well, now there is!
38
Matrix Variables
• Parameters embedded in URI path segments– GET /pets/42;q=21
• Use URI variable where semi-colon content expected– /pets/{petId}
• Extract via annotation– @PathVariable String petId, @MatrixVariable int q
• Some configuration required to enable unless using MVC Java config and MVC namespace
For further details see: http://bit.ly/WBm2ov
39
Spring TestContext Framework Updates
40
What’s New in the Spring TCF?
• Upgraded to JUnit 4.11 and TestNG 6.5.2
• Loading WebApplicationContexts
• Testing request- and session-scoped beans
• Support for ApplicationContextInitializers
• Loading context hierarchies (3.2.1)
• And more… (see presentation from SpringOne 2GX 2012)
41
Loading a WebApplicationContext
• Q: How do you tell the TestContext Framework to load a WebApplicationContext?
• A: Just annotate your test class with @WebAppConfiguration!
42
@WebAppConfiguration
• Denotes that the context should be a WebApplicationContext
• Configures the resource path for the web app– Used by MockServletContext– Defaults to “src/main/webapp”– Paths are file-system folders, relative to the project
root not classpath resources– The classpath: prefix is also supported
43
Example: @WebAppConfiguration
44
Example: @WebAppConfiguration
45
Example: @WebAppConfiguration
46
ServletTestExecutionListener
• Sets up default thread-local state via RequestContextHolder before each test method
• Creates: – MockHttpServletRequest– MockHttpServletResponse– ServletWebRequest
• Ensures that the MockHttpServletResponse and ServletWebRequest can be injected into the test instance
• Cleans up thread-local state after each test method
47
Example: Injecting Mocks
48
Web Scopes – Review
• request: lifecycle tied to the current HttpServletRequest
• session: lifecycle tied to the current HttpSession
49
Example: Request-scoped Bean Config
50
Example: Request-scoped Bean Test
51
Example: Session-scoped Bean Config
52
Example: Session-scoped Bean Test
53
ApplicationContextInitalizer
• Introduced in Spring 3.1• Used for programmatic initialization of a
ConfigurableApplicationContext• For example:
– to register property sources– to activate profiles against the Environment
• Configured in web.xml by specifying contextInitializerClasses via – context-param for the ContextLoaderListener– init-param for the DispatcherServlet
54
Using Initializers in Tests
• Configured in @ContextConfiguration via the initializers attribute
• Inheritance can be controlled via the inheritInitializers attribute
• An ApplicationContextInitializer may configure the entire context – XML resource locations or annotated classes are no
longer required• Initializers are now part of the context cache key• Initializers are ordered based on Spring's Ordered
interface or the @Order annotation
55
Example: Multiple Initializers
56
Application Context Hierarchies
• Currently only flat, non-hierarchical contexts are supported in tests.
• There’s no easy way to create contexts with parent-child relationships.
• But… hierarchies are supported in production.
• Wouldn’t it be nice if you could test them, too?!
57
Testing Context Hierarchies in 3.2.2
• New @ContextHierarchy annotation– Used in conjunction with @ContextConfiguration
• @ContextConfiguration now supports a ‘name’ attribute– for merging and overriding hierarchy configuration
58
Single Test with Context Hierarchy
59
Class and Context Hierarchies
60
Spring MVC Test Framework
61
What is Spring MVC Test?
• First class support for testing Spring MVC applications
• Fluent API
• Server-side tests involve the DispatcherServlet
• Client-side tests are RestTemplate based
• Built on spring-test and MockHttpServletRequest/Response
• Servlet container not required
62
Q: Unit or Integration Testing?
63
A: A Bit of Both
• Integration tests for sure• However…
– no Servlet container– MockHttpServletRequest/Response– Controllers can be injected with mocks
• Also there are two setup options– Load WebApplicationContext as usual– Standalone setup … no Spring configuration, just
controller instance!
• Controller unit testing ++
64
Server-side Test: webAppContextSetup
65
Server-side Test: standaloneSetup
66
Client-side Test
67
Spring MVC Test – Resources
• Blog post– http://bit.ly/QCKMzh
• Samples– https://github.com/SpringSource/spring-mvc-showcase– http://bit.ly/VN1bPw … sample server tests– http://bit.ly/13koRQP … sample client tests
• Reference documentation– http://bit.ly/SmUtD6
68
Roadmap for Spring 4.0
69
1st Class Support for Java 8 based apps
• Language features such as lambda expressions– for callbacks with templates– for concurrent execution
• think fork/join, map/reduce, etc.
• APIs such as JSR-310 Date and Time– Alongside Spring’s existing support for JodaTime
70
Configuring Spring with Groovy 2
• Configuring and implementing Spring-style applications using Groovy 2.x
• Groovy-based bean definitions
• Groovy as the language of choice for an entire application, as a direct and straightforward alternative to Java source files
• Groovy 2.0's static compilation support completes the picture here
71
Support for Key Java EE 7 Technologies
• JMS 2.0
• JPA 2.1
• Bean Validation 1.1
• Servlet 3.1
• And fully covering JCache 1.0
72
Enabling WebSocket-style Architectures
• Support for JSR-356 compliant runtimes
• Also supporting related technologies
73
Fine-grained Eventing and Messaging
• Introducing fine-grained eventing and messaging within the application
• Building on our existing application event mechanism
• Aligned with our JMS message listener mechanism
74
Pruning and Dependency Upgrades
• Removing a variety of deprecated packages across the framework– See Spring Framework 3.2's deprecations!
• Raising minimum dependencies to Java 6+– Java SE 6+ and Java EE 6+– with some compromises for EE 5++ servers
75
In Closing…
76
Special Thanks to…
• Juergen Hoeller
• Chris Beams
• Rossen Stoyanchev
… for permitting reuse of some of their content in this presentation!
77
Further Resources
• Spring Framework– http://www.springsource.org/spring-framework– Spring Reference Manual– Javadoc
• Spring Forums– http://forum.springframework.org
• Spring JIRA– http://jira.springframework.org
• Spring on GitHub– https://github.com/SpringSource/spring-framework
78
Blogs
• SpringSource Team Blog– http://blog.springsource.com/
• Swiftmind Team Blog– http://www.swiftmind.com/blog/
79
Q & A
Sam Brannen
twitter: @sam_brannenwww.slideshare.net/sbrannenwww.swiftmind.com