SlideShare une entreprise Scribd logo
1  sur  73
© 2013 SpringSource, by VMware
The Spring Update
Josh Long (⻰龙之春)
@starbuxman
joshlong.com
josh.long@springsource.com
slideshare.net/joshlong
Tuesday, June 11, 13
Josh Long (⻰龙之春)
@starbuxman
joshlong.com
josh.long@springsource.com
slideshare.net/joshlong
Josh Long (⻰龙之春)
@starbuxman
joshlong.com
josh.long@springsource.com
slideshare.net/joshlong
Tuesday, June 11, 13
Josh Long (⻰龙之春)
@starbuxman
joshlong.com
josh.long@springsource.com
slideshare.net/joshlong
Contributor To:
•Spring Integration
•Spring Batch
•Spring Hadoop
•Activiti Workflow Engine
Tuesday, June 11, 13
Current and Upcoming: 3.1, 3.2, and 4
§ Spring Framework 3.1 (Dec 2011)
• Environment profiles, Java-based configuration, declarative caching
• Initial Java 7 support, Servlet 3.0 based deployment
§ Spring Framework 3.2 (Dec 2012)
• Gradle-based build, GitHub-based contribution model
• Fully Java 7 oriented, async MVC processing on Servlet 3.0
§ Spring Framework 4 (Q4 2013)
• Comprehensive Java SE 8 support (including lambda expressions)
• Single abstract method types in Spring are well positioned
• Support for Java EE 7 API level and WebSockets
4
Tuesday, June 11, 13
Spring 3.1
5
Tuesday, June 11, 13
6
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
Tuesday, June 11, 13
Not confidential. Tell everyone.
So, What’s All of This Look Like in Code?
7
Tuesday, June 11, 13
Not confidential. Tell everyone.
I want Database Access ... with Hibernate 4 Support
8
@Service
public class CustomerService {
public Customer getCustomerById( long customerId) {
...
}
public Customer createCustomer( String firstName, String lastName, Date date){
...
}
}
Tuesday, June 11, 13
Not confidential. Tell everyone.
I want Database Access ... with Hibernate 4 Support
9
@Service
public class CustomerService {
@Inject
private SessionFactory sessionFactory;
public Customer createCustomer(String firstName,
String lastName,
Date signupDate) {
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setLastName(lastName);
customer.setSignupDate(signupDate);
sessionFactory.getCurrentSession().save(customer);
return customer;
}
}
Tuesday, June 11, 13
Not confidential. Tell everyone.
I want Database Access ... with Hibernate 4 Support
10
@Service
public class CustomerService {
@Inject
private SessionFactory sessionFactory;
@Transactional
public Customer createCustomer(String firstName,
String lastName,
Date signupDate) {
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setLastName(lastName);
customer.setSignupDate(signupDate);
sessionFactory.getCurrentSession().save(customer);
return customer;
}
}
Tuesday, June 11, 13
Not confidential. Tell everyone.
I want Declarative Cache Management...
11
@Service
public class CustomerService {
@Inject
private SessionFactory sessionFactory;
@Transactional(readOnly = true)
@Cacheable(“customers”)
public Customer getCustomerById( long customerId) {
...
}
...
}
Tuesday, June 11, 13
Not confidential. Tell everyone.
I want a RESTful Endpoint...
12
package org.springsource.examples.spring31.web;
..
@Controller
public class CustomerController {
@Inject
private CustomerService customerService;
@RequestMapping(value = "/customer/{id}" )
public HttpEntity<Customer> customerById( @PathVariable Integer id ) {
return new ResponseEntity<Customer>( customerService.getCustomerById( id ), HttpStatus.OK );
}
...
}
Tuesday, June 11, 13
Not confidential. Tell everyone.
...But Where’d the SessionFactory come from?
13
Tuesday, June 11, 13
Not confidential. Tell everyone.
A Quick Primer on Configuration in Spring 3.1
....
<beans>
<tx:annotation-driven transaction-manager = "transactionManager" />
<context:component-scan base-package = "some.package" />
<context:property-placeholder properties = "config.properties" />
<bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name = "sessionFactory" ref = "sessionFactory" />
</bean>
<bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
...
</bean>
<bean id = "dataSource" class = "..SimpleDriverDataSource">
<property name= "userName" value = "${ds.username}"/>
...
</bean>
</beans>
ApplicationContext ctx = new ClassPathXmlApplication( “service-config.xml” );
Tuesday, June 11, 13
Not confidential. Tell everyone.
A Quick Primer on Configuration in Spring 3.1
@Configuration
@PropertySource(“config.properties”)
@EnableTransactionManagement
@ComponentScan
public class ApplicationConfiguration {
@Inject private Environment environment;
@Bean public PlatformTransactionManager transactionManager( SessionFactory sf ){
return new HibernateTransactionManager( sf );
}
@Bean public SessionFactory sessionFactory (){ ... }
@Bean public DataSource dataSource(){
SimpleDriverDataSource sds = new SimpleDriverDataSource();
sds.setUserName( environment.getProperty( “ds.username”));
// ...
return sds;
}
}
ApplicationContext ctx = new AnnotationConfigApplicationContext( ApplicationConfiguration.class );
Tuesday, June 11, 13
16
Bean Definition Profiles
@Configuration
@Profile(“production”)
public class ProductionDataSourceConfiguration {
@Bean public javax.sql.DataSource dataSource(){
return new SimpleDriverDataSource( .. ) ;
}
}
@Configuration
@Profile(“embedded”)
public class LocalDataSourceConfiguration {
@Bean public javax.sql.DataSource dataSource(){
return new EmbeddedDatabaseFactoryBean( ... );
}
}
@Configuration
@Import( { LocalDataSourceConfiguration.class, ProductionDataSourceConfiguration.class } )
public class ServiceConfiguration {
// EmbeddedDatabaseFactoryBean
@Bean public CustomerService customerService( javax.sql.DataSource dataSource ){
// ...
-Dspring.profiles.active=embedded
Tuesday, June 11, 13
17
Bean Definition Profiles
<beans>
<beans profile=”embedded”>
<jdbc:embedded-datasource id= “ds” ... />
</beans>
<beans profile= “production” >
<bean id= “ds” class = “...DataSource” .. />
</beans>
</beans>
-Dspring.profiles.active=embedded
Tuesday, June 11, 13
18
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() {
...
}
}
Tuesday, June 11, 13
19
"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 application's class files
<bean class="…" c:age="10" c:name="myName"/>
<bean class="…" c:name-ref="nameBean" c:spouse-ref="spouseBean"/>
Tuesday, June 11, 13
20
Cache Abstraction
Tuesday, June 11, 13
20
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
Tuesday, June 11, 13
20
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
Tuesday, June 11, 13
20
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
Tuesday, June 11, 13
20
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
Tuesday, June 11, 13
20
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
§ Specific cache setup per environment – through
profiles?
• potentially even adapting to a runtime-provided
service
Tuesday, June 11, 13
20
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
§ Specific cache setup per environment – through
profiles?
• potentially even adapting to a runtime-provided
service
@Cacheable ( name = “owner”)
public Owner loadOwner(int id);
Tuesday, June 11, 13
20
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
§ Specific cache setup per environment – through
profiles?
• potentially even adapting to a runtime-provided
service
@Cacheable ( name = “owner”)
public Owner loadOwner(int id);
@Cacheable(name = “owners”,
condition="name.length < 10")
Tuesday, June 11, 13
20
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
§ Specific cache setup per environment – through
profiles?
• potentially even adapting to a runtime-provided
service
@Cacheable ( name = “owner”)
public Owner loadOwner(int id);
@Cacheable(name = “owners”,
condition="name.length < 10")
public Owner loadOwner(String name);
Tuesday, June 11, 13
20
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
§ Specific cache setup per environment – through
profiles?
• potentially even adapting to a runtime-provided
service
@Cacheable ( name = “owner”)
public Owner loadOwner(int id);
@Cacheable(name = “owners”,
condition="name.length < 10")
public Owner loadOwner(String name);
@CacheEvict (name = “owners”)
Tuesday, June 11, 13
20
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
§ Specific cache setup per environment – through
profiles?
• potentially even adapting to a runtime-provided
service
@Cacheable ( name = “owner”)
public Owner loadOwner(int id);
@Cacheable(name = “owners”,
condition="name.length < 10")
public Owner loadOwner(String name);
@CacheEvict (name = “owners”)
public void deleteOwner(int id);
Tuesday, June 11, 13
21
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.0's ServletContainerInitializer mechanism
• in combination with Spring 3.1's AnnotationConfigWebApplicationContext
• plus Spring 3.1's environment abstraction
§ Exposure of native Servlet 3.0 functionality in Spring MVC
• standard Servlet 3.0 file upload behind Spring's MultipartResolver abstraction
• support for asynchronous request processing coming in Spring 3.2
Tuesday, June 11, 13
22
WebApplicationInitializer Example
/**
Automatically detected and invoked on startup by Spring's
ServletContainerInitializer. May register listeners, filters,
servlets etc against the given Servlet 3.0 ServletContext.
*/
public class MyApplicationWebApplicationInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext sc) throws ServletException {
// create ‘root’ Spring ApplicationContext
AnnotationConfigWebApplicationContext root = root AnnotationConfigWebApplicationContext();
root.scan("com.mycompany.myapp");
root.register(FurtherConfig.class);
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
}
}
Tuesday, June 11, 13
23
@MVC Processing & Flash Attributes
Tuesday, June 11, 13
23
@MVC Processing & Flash Attributes
§ RequestMethodHandlerAdapter
l arbitrary mappings to handler methods across multiple controllers
l better customization of handler method arguments
− HandlerMethodArgumentResolver
− HandlerMethodReturnValueHandler
− etc
Tuesday, June 11, 13
23
@MVC Processing & Flash Attributes
§ RequestMethodHandlerAdapter
l arbitrary mappings to handler methods across multiple controllers
l better customization of handler method arguments
− HandlerMethodArgumentResolver
− HandlerMethodReturnValueHandler
− etc
§ FlashMap support and FlashMapManager abstraction
l with RedirectAttributes as a new @MVC handler method argument type
− explicitly calling addFlashAttribute to add values to the output FlashMap
l an outgoing FlashMap will temporarily get added to the user's session
l an incoming FlashMap for a request will automatically get exposed to the model
Tuesday, June 11, 13
github.com/SpringSource
24
Tuesday, June 11, 13
Spring 3.2
25
Tuesday, June 11, 13
Change of Plans
§ We originally meant to have Java SE 8 and Java EE 7 themes in Spring 3.2
§ However, Java EE 7 got pushed out further and further: Q2 2013
• eventually descoped and delayed (no cloud focus anymore)
§ And Java SE 8 (OpenJDK 8) got rescheduled as well: September 2013 Q1 2014
• once again, descoped and delayed (no module system anymore)
• feature-complete developer preview expected for February 2013
§ Our solution: Spring 3.2 ships in Q4 2012 with core framework refinements
• Spring 3.3 will ship in Q4 2013 with Java SE 8 and Java EE 7 support.
26
Tuesday, June 11, 13
So what’s in 3.2?
§ Gradle-based build
§ Binaries built against Java 7
§ Inlined ASM 4.0 and CGLIB 3.0
§ Async MVC processing on Servlet 3.0
§ Spring MVC test support
§ MVC configuration refinements
§ SpEL refinements
§ Also including many runtime refinements
• partially back-ported to 3.1.2/3.1.3
§ General Spring MVC niceties
• Servlet 3 async support
• error reporting in REST scenarios
• content negotiation strategies
• matrix variables
27
Tuesday, June 11, 13
Async MVC Processing: Callable
28
@RequestMapping(name =“/upload”,
method=RequestMethod.POST)
public Callable<String> processUpload(MultipartFile file) {
return new Callable<String>() {
public String call() throws Exception {
// ...
return "someView";
}
};
}
- thread managed by Spring MVC
- good for long running database jobs, 3rd party REST API calls, etc
Tuesday, June 11, 13
Async MVC Processing: DeferredResult
29
@RequestMapping("/quotes")
@ResponseBody
public DeferredResult quotes() {
DeferredResult deferredResult = new DeferredResult();
// Add deferredResult to a Queue or a Map...
return deferredResult;
}
// In some other thread:
// Set the return value on the DeferredResult deferredResult.set(data);
- thread managed outside of Spring MVC
- JMS or AMQP message listener, another HTTP request, etc.
Tuesday, June 11, 13
Async MVC Processing: AsyncTask
30
@RequestMapping(name =“/upload”, method=RequestMethod.POST)
public AsyncTask<Foo> processUpload(MultipartFile file) {
TaskExecutor asyncTaskExecutor = new AsyncTaskExecutor(...);
return new AsyncTask<Foo>(
1000L, // timeout
asyncTaskExecutor, // thread pool
new Callable<Foo>(){ ..} // thread
);
}
- same as Callable, with extra features
- override timeout value for async processing
- lets you specify a specific AsyncTaskExecutor
Tuesday, June 11, 13
Content Negotiation Strategies
31
ContentNegotiationStrategy
• By 'Accept' Header
• By URL extension (.xml, .json, etc)
• By Request parameter, i.e. /accounts/1?format=json
• Fixed content type, i.e. a fallback option
ContentNegotiationManager
• has one or more ContentNegotiationStrategy instances
• works with:
RequestMappingHandlerMapping,
RequestMappingHandlerAdapter,
ExceptionHandlerExceptionResolver
ContentNegotiatingViewResolver
Tuesday, June 11, 13
Matrix Variables
32
"Each path segment may include a
sequence of parameters, indicated by the
semicolon ";" character. The parameters
are not significant to the parsing of
relativeb references.
RFC 2396, section 3.3
Tuesday, June 11, 13
Matrix Variables
33
"The semicolon (";") and equals ("=") reserved characters
are often used to delimit parameters and
parameter values applicable to that segment. The
comma (",") reserved character is often used for
similar purposes."
RFC 3986, section 3.3
Tuesday, June 11, 13
Matrix Variables
§ Two Types of Usages
§ Path Segment Name-Value Pairs
§ As delimited list path segment
34
/qa-releases;buildNumber=135;revision=3.2
/answers/id1;id2;id3;id4/comments
Tuesday, June 11, 13
Matrix Variables: the common case
35
// GET /pets/42;q=11;r=22
@RequestMapping(value = "/pets/{petId}")
public void findPet(
@PathVariable String petId, @MatrixVariable int q) {
// petId == 42
// q == 11
}
Tuesday, June 11, 13
Matrix Variables: obtain all matrix variables
36
// GET /owners/42;q=11;r=12/pets/21;q=22;s=23
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}")
public void findPet(
@MatrixVariable Map<String, String> matrixVars) {
// matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]
}
Tuesday, June 11, 13
Matrix Variables: qualify path segment
37
// GET /owners/42;q=11/pets/21;q=22
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}")
public void findPet(
@MatrixVariable(value="q", pathVar="ownerId") int q1,
@MatrixVariable(value="q", pathVar="petId") int q2) {
// q1 == 11
// q2 == 22
}
Tuesday, June 11, 13
38
MVC Test Framework Server
import ... MockMvcBuilders.* ;
import ... MockMvcRequestBuilders.*;
import ... MockMvcResultMatchers.*;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("servlet-context.xml")
public class SampleTests {
 
  @Autowired
  private WebApplicationContext wac;
 
  private MockMvc mockMvc;
 
  @Before
  public void setup() {
    this.mockMvc = webAppContextSetup(this.wac).build();
  }
 
  @Test
  public void getFoo() throws Exception {
    this.mockMvc.perform(get("/foo").accept("application/json"))
        .andExpect(status().isOk())
        .andExpect(content().mimeType("application/json"))
        .andExpect(jsonPath("$.name").value("Lee"));
  }
}
Tuesday, June 11, 13
39
MVC Test Framework Client
RestTemplate restTemplate = new RestTemplate();
MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
 
mockServer.expect(requestTo("/greeting"))
  .andRespond(withSuccess("Hello world", "text/plain"));
 
// use RestTemplate ...
 
mockServer.verify();
Tuesday, June 11, 13
Spring 4
40
Tuesday, June 11, 13
Spring Framework 4 (Q4 2013)
§ Comprehensive Java 8 support
• Support for Java EE 7 API levels
• Focus on message-oriented architectures
• annotation-driven JMS endpoint model
§ revised application event mechanism
§ WebSocket support in Spring MVC
§ Next-generation Groovy support
§ Grails bean builder finally making it into Spring proper
41
Tuesday, June 11, 13
42
§ you can follow along at home..
Spring Framework 4 (Q4 2013)
Tuesday, June 11, 13
The Java SE 8 and Java EE 7 Story
§ Comprehensive Java 8 support
• lambda expressions a.k.a. closures
• Date and Time API (JSR-310)
• NIO-based HTTP client APIs
• parameter name discovery
• java.util.concurrent enhancements
§ Support for Java EE 7 API levels
• JCache 1.0
• JMS 2.0
• JPA2.1
• JTA 1.2 (@Transactional)
• Bean Validation 1.1
• Servlet3.1
• JSF 2.2
43
§ Retaining support for Java 5 and higher
• with Java 6 and 7 as common levels
• Java 8 potentially becoming popular rather quickly...
Tuesday, June 11, 13
Resource Caching
§ expanding mvc:resources
§ Support for pre-processing resources
§ Might look similar to the Grails resource pipeline
44
Tuesday, June 11, 13
Groovy Support
§ Groovy BeanBuilder might make it into Spring 4 core
§ Enhanced language level support
45
Tuesday, June 11, 13
@Conditional
46
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface Conditional {
	 /**
	 * All {@link Condition}s that must {@linkplain Condition#matches match} in order for
	 * the component to be registered.
	 */
	 Class<? extends Condition>[] value();
}
public interface Condition {
	 /**
	 * Determine if the condition matches.
	 * @param context the condition context
	 * @param metadata meta-data of the {@link AnnotationMetadata class} or
	 * {@link MethodMethod method} being checked.
	 * @return {@code true} if the condition matches and the component can be registered
	 * or {@code false} to veto registration.
	 */
	 boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);
}
Tuesday, June 11, 13
JDK 8 Support In-Depth
§ implicit use of LinkedHash{Map|Set} instead of HashMap/Set to preserver ordering diffs in JDK 7 and JDK 8
§ Embed ASM 4.1 into Spring codebase to
support JDK8 bytecode changes and to keep compatability cglib 3.0
§ JDK 8 Date and Time (JSR 310)
§ add awatTerminationSeconds / commonPool properties to ForkJoinPoolFactoryBean to support JDK
8 changes
§ Incorporate JDK 8 reflection support (java.lang.reflect.Parameter)
47
Tuesday, June 11, 13
JMS 2.0 Support
48
<jms:annotation-driven>
@JmsListener(destination="myQueue")
public void handleMessage(TextMessage payload);
@JmsListener(destination="myQueue", selector="...")
public void handleMessage(String payload);
@JmsListener(destination="myQueue")
public String handleMessage(String payload);
Tuesday, June 11, 13
Bean Validation 1.1 Support in Spring
49
§ now works with Hibernate Validator 5
§ MethodValidationInterceptor auto-detects Bean Validation 1.1's ExecutableValidator API now
and uses it in favor of Hibernate Validator 4.2's native variant.
Tuesday, June 11, 13
JSR 236 (ManagedExecutorService) support
50
• ConcurrentTask(Executor|Scheduler) now automatically detect a
JSR 236 ManagedExecutorService and adapt them
Tuesday, June 11, 13
• simplest case: let JSR 356 scan for your endpoint
• drawback: scanning takes a long time
Web Sockets Support (JSR-356) - Servlet scanning
51
import javax.websocket.server.ServerEndpoint;
import org.springframework.web.socket.server.endpoint. SpringConfigurator. 
@ServerEndpoint(value = "/echo", configurator = SpringConfigurator.class)
public class EchoEndpoint {
 
  private final EchoService echoService;
 
  @Autowired
  public EchoEndpoint(EchoService echoService) {
    this.echoService = echoService;
  }
 
  @OnMessage
  public void handleMessage(Session session, String message) {
    // ...
  }
 
}
Tuesday, June 11, 13
Web Sockets Support (JSR-356) - Spring container-centric registration (you can turn off scan)
52
import org.springframework.web.socket.server.endpoint.ServerEndpointExporter;
import org.springframework.web.socket.server.endpoint.ServerEndpointRegistration;
 
@Configuration
public class EndpointConfig {
@Bean public EchoService service(){ ... }
 
  @Bean
  public EchoEndpoint echoEndpoint(EchoService service) {
    return new EchoEndpoint(service );
  }
 
// once per application
  @Bean
  public ServerEndpointExporter endpointExporter() {
    return new ServerEndpointExporter();
  }
  
}
Tuesday, June 11, 13
import org.springframework.web.socket.server.endpoint.ServerEndpointExporter;
import org.springframework.web.socket.server.endpoint.ServerEndpointRegistration;
 
@Configuration
public class EndpointConfig {
@Bean public EchoService service(){ ... }
 
@Bean public EchoEndpoint endpoint(EchoService service) {
return new EchoEndpoint( service );
}
  @Bean  public EndpointRegistration echoEndpointRegistration (EchoEndpoint eep ) {
    return new EndpointRegistration(“/echo”, eep );
  }
 
// once per application
  @Bean
  public ServerEndpointExporter endpointExporter() {
    return new ServerEndpointExporter();
  }
}
Web Sockets Support (JSR-356) - Spring container-centric registration (you can turn off scan)
endpoint class endpoint instance
instance per socket Spring scope
Tuesday, June 11, 13
Web Sockets Support (Spring Web Sockets Abstraction)
54
§ rooted in org.springframework.web.socket
§ not meant to be consumed directly, too low level.
§ A good practice is one handler (and one web socket) per application.
§ You’d have to handle all requests with one class and handler.
§ (Imagine REST without verbs, too limited!)
§ This begs for a higher level API with annotations.
§ Basis for other support, including SockJS
§ More flexible API, first (and likely permanent) implementation based on Jetty 9
§ implementation based on Jetty 9
§ API rooted at WebSocketHandler
Tuesday, June 11, 13
import org.springframework.web.socket.adapter.TextWebSocketHandlerAdapter;
 
public class EchoHandler extends TextWebSocketHandlerAdapter {
 
  @Override
  public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
    session.sendMessage(message);
  }
 
}
Web Sockets Support (Spring Web Sockets Abstraction - WebSocketHandler)
Tuesday, June 11, 13
import org.springframework.web.socket.server.support. WebSocketHttpRequestHandler;
 
@Configuration
public class WebConfig {
@Bean public EchoHandler handler(){ ... }
 
  @Bean
  public SimpleUrlHandlerMapping handlerMapping(EchoHandler handler ) {
 
    Map<String, Object> urlMap = new HashMap<String, Object>();
    urlMap.put("/echo", new WebSocketHttpRequestHandler( handler ));
 
    SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping();
    hm.setUrlMap(urlMap);
    return hm;
  }
 
}
Web Sockets Support (Spring Web Sockets Abstraction - WebSocketHandler)
Tuesday, June 11, 13
import org.springframework.web.socket.sockjs.SockJsService;
// ...
 
@Configuration
public class WebConfig {
 
  @Bean
  public SimpleUrlHandlerMapping handlerMapping( EchoHandler handler, TaskScheduler ts ) {
 
    SockJsService sockJsService = new DefaultSockJsService( ts );
 
    Map<String, Object> urlMap = new HashMap<String, Object>();
    urlMap.put("/echo/**", new SockJsHttpRequestHandler(sockJsService, handler ));
 
    SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping();
    hm.setUrlMap(urlMap);
    return hm;
  }
 
  @Bean  public TaskScheduler taskScheduler() { ... }
 
}
Web Sockets Support (Spring Web Sockets Abstraction - SockJS)
Tuesday, June 11, 13
import org.springframework.web.socket.client.endpoint.AnnotatedEndpointConnectionManager;
 
@Configuration
public class EndpointConfig {
 
  // For Endpoint sub-classes use EndpointConnectionManager instead
 
  @Bean
  public AnnotatedEndpointConnectionManager connectionManager(EchoEndpoint endpoint) {
    return new AnnotatedEndpointConnectionManager(
endpoint, "ws://localhost:8080/webapp/echo");
  }
 
  @Bean
  public EchoEndpoint echoEndpoint() {
    // ...
  }
 
}
Web Sockets Support (client side)
Tuesday, June 11, 13
JMS 2.0 Support
59
• Added "deliveryDelay" property on JmsTemplate
• Added support for "deliveryDelay" and CompletionListener to CachedMessageProducer
• Added support for the new "create(Shared)DurableConsumer" variants in Spring’s
CachingConnectionFactory
• Added support for the new "createSession" variants with fewer parameters in Spring’s
SingleConnectionFactory
Tuesday, June 11, 13
Current and Upcoming: 3.1, 3.2, and 3.2
§ Spring Framework 3.1 (Dec 2011)
• Environment profiles, Java-based configuration, declarative caching
• Initial Java 7 support, Servlet 3.0 based deployment
§ Spring Framework 3.2 (Dec 2012)
• Gradle-based build, GitHub-based contribution model
• Fully Java 7 oriented, async MVC processing on Servlet 3.0
§ Spring Framework 3.3 (Q4 2013)
• Comprehensive Java SE 8 support (including lambda expressions)
• Support for Java EE 7 API level and WebSockets
60
Tuesday, June 11, 13
NOT CONFIDENTIAL -- TELL EVERYONE
@SpringSource @Starbuxman
Questions?
Tuesday, June 11, 13

Contenu connexe

Tendances

Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot IntroductionJeevesh Pandey
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring SessionDavid Gómez García
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Oscar Renalias
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadWASdev Community
 
Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdatePhil Steitz
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservicesNilanjan Roy
 
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphere
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphereAAI 2236-Using the New Java Concurrency Utilities with IBM WebSphere
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphereKevin Sutter
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, mavenFahad Golra
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerZeroTurnaround
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJiayun Zhou
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)Fahad Golra
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RSFahad Golra
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session ManagementFahad Golra
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutesglassfish
 

Tendances (18)

Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Connection Pooling
Connection PoolingConnection Pooling
Connection Pooling
 
Managing user's data with Spring Session
Managing user's data with Spring SessionManaging user's data with Spring Session
Managing user's data with Spring Session
 
Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0Asynchronous web apps with the Play Framework 2.0
Asynchronous web apps with the Play Framework 2.0
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 InsteadDon't Wait! Develop Responsive Applications with Java EE7 Instead
Don't Wait! Develop Responsive Applications with Java EE7 Instead
 
Apache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 UpdateApache Commons Pool and DBCP - Version 2 Update
Apache Commons Pool and DBCP - Version 2 Update
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot for buidling microservices
Spring boot for buidling microservicesSpring boot for buidling microservices
Spring boot for buidling microservices
 
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphere
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphereAAI 2236-Using the New Java Concurrency Utilities with IBM WebSphere
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphere
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen Hoeller
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Java EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSFJava EE 6 CDI Integrates with Spring & JSF
Java EE 6 CDI Integrates with Spring & JSF
 
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)Lecture 4:  JavaServer Pages (JSP) & Expression Language (EL)
Lecture 4: JavaServer Pages (JSP) & Expression Language (EL)
 
Lecture 7 Web Services JAX-WS & JAX-RS
Lecture 7   Web Services JAX-WS & JAX-RSLecture 7   Web Services JAX-WS & JAX-RS
Lecture 7 Web Services JAX-WS & JAX-RS
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Fifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 MinutesFifty Features of Java EE 7 in 50 Minutes
Fifty Features of Java EE 7 in 50 Minutes
 

Similaire à Spring Framework 3.1 Update

The Spring 4 Update - Josh Long
The Spring 4 Update - Josh LongThe Spring 4 Update - Josh Long
The Spring 4 Update - Josh Longjaxconf
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
spring3.2 java config Servler3
spring3.2 java config Servler3spring3.2 java config Servler3
spring3.2 java config Servler3YongHyuk Lee
 
Connect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and JavaConnect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and JavaJulian Robichaux
 
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...panagenda
 
#GeodeSummit - Spring Data GemFire API Current and Future
#GeodeSummit - Spring Data GemFire API Current and Future#GeodeSummit - Spring Data GemFire API Current and Future
#GeodeSummit - Spring Data GemFire API Current and FuturePivotalOpenSourceHub
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long jaxconf
 
CloudStack Meetup Santa Clara
CloudStack Meetup Santa Clara CloudStack Meetup Santa Clara
CloudStack Meetup Santa Clara NetApp
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
Storage Plug-ins
Storage Plug-ins Storage Plug-ins
Storage Plug-ins buildacloud
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenJoshua Long
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injectionsrmelody
 
Solid fire cloudstack storage overview - CloudStack European User Group
Solid fire cloudstack storage overview - CloudStack European User GroupSolid fire cloudstack storage overview - CloudStack European User Group
Solid fire cloudstack storage overview - CloudStack European User GroupShapeBlue
 
CloudStack Meetup London - Primary Storage Presentation by SolidFire
CloudStack Meetup London - Primary Storage Presentation by SolidFire CloudStack Meetup London - Primary Storage Presentation by SolidFire
CloudStack Meetup London - Primary Storage Presentation by SolidFire NetApp
 
GlassFish REST Administration Backend
GlassFish REST Administration BackendGlassFish REST Administration Backend
GlassFish REST Administration BackendArun Gupta
 
Writing Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason LeeWriting Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason Leejaxconf
 
GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012Arun Gupta
 

Similaire à Spring Framework 3.1 Update (20)

The Spring 4 Update - Josh Long
The Spring 4 Update - Josh LongThe Spring 4 Update - Josh Long
The Spring 4 Update - Josh Long
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
spring3.2 java config Servler3
spring3.2 java config Servler3spring3.2 java config Servler3
spring3.2 java config Servler3
 
Connect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and JavaConnect2016 AD1387 Integrate with XPages and Java
Connect2016 AD1387 Integrate with XPages and Java
 
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
AD1387: Outside The Box: Integrating with Non-Domino Apps using XPages and Ja...
 
#GeodeSummit - Spring Data GemFire API Current and Future
#GeodeSummit - Spring Data GemFire API Current and Future#GeodeSummit - Spring Data GemFire API Current and Future
#GeodeSummit - Spring Data GemFire API Current and Future
 
Spring.io
Spring.ioSpring.io
Spring.io
 
Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long Multi Client Development with Spring - Josh Long
Multi Client Development with Spring - Josh Long
 
Spring 3.1
Spring 3.1Spring 3.1
Spring 3.1
 
CloudStack Meetup Santa Clara
CloudStack Meetup Santa Clara CloudStack Meetup Santa Clara
CloudStack Meetup Santa Clara
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Storage Plug-ins
Storage Plug-ins Storage Plug-ins
Storage Plug-ins
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring dependency injection
Spring dependency injectionSpring dependency injection
Spring dependency injection
 
Solid fire cloudstack storage overview - CloudStack European User Group
Solid fire cloudstack storage overview - CloudStack European User GroupSolid fire cloudstack storage overview - CloudStack European User Group
Solid fire cloudstack storage overview - CloudStack European User Group
 
CloudStack Meetup London - Primary Storage Presentation by SolidFire
CloudStack Meetup London - Primary Storage Presentation by SolidFire CloudStack Meetup London - Primary Storage Presentation by SolidFire
CloudStack Meetup London - Primary Storage Presentation by SolidFire
 
GlassFish REST Administration Backend
GlassFish REST Administration BackendGlassFish REST Administration Backend
GlassFish REST Administration Backend
 
Writing Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason LeeWriting Plugged-in Java EE Apps: Jason Lee
Writing Plugged-in Java EE Apps: Jason Lee
 
GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012GlassFish REST Administration Backend at JavaOne India 2012
GlassFish REST Administration Backend at JavaOne India 2012
 

Plus de Joshua Long

Economies of Scaling Software
Economies of Scaling SoftwareEconomies of Scaling Software
Economies of Scaling SoftwareJoshua Long
 
Bootiful Code with Spring Boot
Bootiful Code with Spring BootBootiful Code with Spring Boot
Bootiful Code with Spring BootJoshua Long
 
Microservices with Spring Boot
Microservices with Spring BootMicroservices with Spring Boot
Microservices with Spring BootJoshua Long
 
Have You Seen Spring Lately?
Have You Seen Spring Lately?Have You Seen Spring Lately?
Have You Seen Spring Lately?Joshua Long
 
the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013Joshua Long
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonJoshua Long
 
Extending spring
Extending springExtending spring
Extending springJoshua Long
 
The spring 32 update final
The spring 32 update finalThe spring 32 update final
The spring 32 update finalJoshua Long
 
Integration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud FoundryIntegration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud FoundryJoshua Long
 
using Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundryusing Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud FoundryJoshua Long
 
Spring in-the-cloud
Spring in-the-cloudSpring in-the-cloud
Spring in-the-cloudJoshua Long
 
The Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - EuropeThe Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - EuropeJoshua Long
 
A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom Joshua Long
 
Multi client Development with Spring
Multi client Development with SpringMulti client Development with Spring
Multi client Development with SpringJoshua Long
 
Spring Batch Behind the Scenes
Spring Batch Behind the ScenesSpring Batch Behind the Scenes
Spring Batch Behind the ScenesJoshua Long
 
Cloud Foundry Bootcamp
Cloud Foundry BootcampCloud Foundry Bootcamp
Cloud Foundry BootcampJoshua Long
 
Spring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundrySpring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundryJoshua Long
 
Extending Spring for Custom Usage
Extending Spring for Custom UsageExtending Spring for Custom Usage
Extending Spring for Custom UsageJoshua Long
 
Using Spring's IOC Model
Using Spring's IOC ModelUsing Spring's IOC Model
Using Spring's IOC ModelJoshua Long
 

Plus de Joshua Long (20)

Economies of Scaling Software
Economies of Scaling SoftwareEconomies of Scaling Software
Economies of Scaling Software
 
Bootiful Code with Spring Boot
Bootiful Code with Spring BootBootiful Code with Spring Boot
Bootiful Code with Spring Boot
 
Microservices with Spring Boot
Microservices with Spring BootMicroservices with Spring Boot
Microservices with Spring Boot
 
Boot It Up
Boot It UpBoot It Up
Boot It Up
 
Have You Seen Spring Lately?
Have You Seen Spring Lately?Have You Seen Spring Lately?
Have You Seen Spring Lately?
 
the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013the Spring Update from JavaOne 2013
the Spring Update from JavaOne 2013
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
 
Extending spring
Extending springExtending spring
Extending spring
 
The spring 32 update final
The spring 32 update finalThe spring 32 update final
The spring 32 update final
 
Integration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud FoundryIntegration and Batch Processing on Cloud Foundry
Integration and Batch Processing on Cloud Foundry
 
using Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundryusing Spring and MongoDB on Cloud Foundry
using Spring and MongoDB on Cloud Foundry
 
Spring in-the-cloud
Spring in-the-cloudSpring in-the-cloud
Spring in-the-cloud
 
The Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - EuropeThe Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
The Cloud Foundry bootcamp talk from SpringOne On The Road - Europe
 
A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom A Walking Tour of (almost) all of Springdom
A Walking Tour of (almost) all of Springdom
 
Multi client Development with Spring
Multi client Development with SpringMulti client Development with Spring
Multi client Development with Spring
 
Spring Batch Behind the Scenes
Spring Batch Behind the ScenesSpring Batch Behind the Scenes
Spring Batch Behind the Scenes
 
Cloud Foundry Bootcamp
Cloud Foundry BootcampCloud Foundry Bootcamp
Cloud Foundry Bootcamp
 
Spring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud FoundrySpring in the Cloud - using Spring with Cloud Foundry
Spring in the Cloud - using Spring with Cloud Foundry
 
Extending Spring for Custom Usage
Extending Spring for Custom UsageExtending Spring for Custom Usage
Extending Spring for Custom Usage
 
Using Spring's IOC Model
Using Spring's IOC ModelUsing Spring's IOC Model
Using Spring's IOC Model
 

Dernier

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 

Dernier (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 

Spring Framework 3.1 Update

  • 1. © 2013 SpringSource, by VMware The Spring Update Josh Long (⻰龙之春) @starbuxman joshlong.com josh.long@springsource.com slideshare.net/joshlong Tuesday, June 11, 13
  • 2. Josh Long (⻰龙之春) @starbuxman joshlong.com josh.long@springsource.com slideshare.net/joshlong Josh Long (⻰龙之春) @starbuxman joshlong.com josh.long@springsource.com slideshare.net/joshlong Tuesday, June 11, 13
  • 3. Josh Long (⻰龙之春) @starbuxman joshlong.com josh.long@springsource.com slideshare.net/joshlong Contributor To: •Spring Integration •Spring Batch •Spring Hadoop •Activiti Workflow Engine Tuesday, June 11, 13
  • 4. Current and Upcoming: 3.1, 3.2, and 4 § Spring Framework 3.1 (Dec 2011) • Environment profiles, Java-based configuration, declarative caching • Initial Java 7 support, Servlet 3.0 based deployment § Spring Framework 3.2 (Dec 2012) • Gradle-based build, GitHub-based contribution model • Fully Java 7 oriented, async MVC processing on Servlet 3.0 § Spring Framework 4 (Q4 2013) • Comprehensive Java SE 8 support (including lambda expressions) • Single abstract method types in Spring are well positioned • Support for Java EE 7 API level and WebSockets 4 Tuesday, June 11, 13
  • 6. 6 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 Tuesday, June 11, 13
  • 7. Not confidential. Tell everyone. So, What’s All of This Look Like in Code? 7 Tuesday, June 11, 13
  • 8. Not confidential. Tell everyone. I want Database Access ... with Hibernate 4 Support 8 @Service public class CustomerService { public Customer getCustomerById( long customerId) { ... } public Customer createCustomer( String firstName, String lastName, Date date){ ... } } Tuesday, June 11, 13
  • 9. Not confidential. Tell everyone. I want Database Access ... with Hibernate 4 Support 9 @Service public class CustomerService { @Inject private SessionFactory sessionFactory; public Customer createCustomer(String firstName, String lastName, Date signupDate) { Customer customer = new Customer(); customer.setFirstName(firstName); customer.setLastName(lastName); customer.setSignupDate(signupDate); sessionFactory.getCurrentSession().save(customer); return customer; } } Tuesday, June 11, 13
  • 10. Not confidential. Tell everyone. I want Database Access ... with Hibernate 4 Support 10 @Service public class CustomerService { @Inject private SessionFactory sessionFactory; @Transactional public Customer createCustomer(String firstName, String lastName, Date signupDate) { Customer customer = new Customer(); customer.setFirstName(firstName); customer.setLastName(lastName); customer.setSignupDate(signupDate); sessionFactory.getCurrentSession().save(customer); return customer; } } Tuesday, June 11, 13
  • 11. Not confidential. Tell everyone. I want Declarative Cache Management... 11 @Service public class CustomerService { @Inject private SessionFactory sessionFactory; @Transactional(readOnly = true) @Cacheable(“customers”) public Customer getCustomerById( long customerId) { ... } ... } Tuesday, June 11, 13
  • 12. Not confidential. Tell everyone. I want a RESTful Endpoint... 12 package org.springsource.examples.spring31.web; .. @Controller public class CustomerController { @Inject private CustomerService customerService; @RequestMapping(value = "/customer/{id}" ) public HttpEntity<Customer> customerById( @PathVariable Integer id ) { return new ResponseEntity<Customer>( customerService.getCustomerById( id ), HttpStatus.OK ); } ... } Tuesday, June 11, 13
  • 13. Not confidential. Tell everyone. ...But Where’d the SessionFactory come from? 13 Tuesday, June 11, 13
  • 14. Not confidential. Tell everyone. A Quick Primer on Configuration in Spring 3.1 .... <beans> <tx:annotation-driven transaction-manager = "transactionManager" /> <context:component-scan base-package = "some.package" /> <context:property-placeholder properties = "config.properties" /> <bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name = "sessionFactory" ref = "sessionFactory" /> </bean> <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean"> ... </bean> <bean id = "dataSource" class = "..SimpleDriverDataSource"> <property name= "userName" value = "${ds.username}"/> ... </bean> </beans> ApplicationContext ctx = new ClassPathXmlApplication( “service-config.xml” ); Tuesday, June 11, 13
  • 15. Not confidential. Tell everyone. A Quick Primer on Configuration in Spring 3.1 @Configuration @PropertySource(“config.properties”) @EnableTransactionManagement @ComponentScan public class ApplicationConfiguration { @Inject private Environment environment; @Bean public PlatformTransactionManager transactionManager( SessionFactory sf ){ return new HibernateTransactionManager( sf ); } @Bean public SessionFactory sessionFactory (){ ... } @Bean public DataSource dataSource(){ SimpleDriverDataSource sds = new SimpleDriverDataSource(); sds.setUserName( environment.getProperty( “ds.username”)); // ... return sds; } } ApplicationContext ctx = new AnnotationConfigApplicationContext( ApplicationConfiguration.class ); Tuesday, June 11, 13
  • 16. 16 Bean Definition Profiles @Configuration @Profile(“production”) public class ProductionDataSourceConfiguration { @Bean public javax.sql.DataSource dataSource(){ return new SimpleDriverDataSource( .. ) ; } } @Configuration @Profile(“embedded”) public class LocalDataSourceConfiguration { @Bean public javax.sql.DataSource dataSource(){ return new EmbeddedDatabaseFactoryBean( ... ); } } @Configuration @Import( { LocalDataSourceConfiguration.class, ProductionDataSourceConfiguration.class } ) public class ServiceConfiguration { // EmbeddedDatabaseFactoryBean @Bean public CustomerService customerService( javax.sql.DataSource dataSource ){ // ... -Dspring.profiles.active=embedded Tuesday, June 11, 13
  • 17. 17 Bean Definition Profiles <beans> <beans profile=”embedded”> <jdbc:embedded-datasource id= “ds” ... /> </beans> <beans profile= “production” > <bean id= “ds” class = “...DataSource” .. /> </beans> </beans> -Dspring.profiles.active=embedded Tuesday, June 11, 13
  • 18. 18 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() { ... } } Tuesday, June 11, 13
  • 19. 19 "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 application's class files <bean class="…" c:age="10" c:name="myName"/> <bean class="…" c:name-ref="nameBean" c:spouse-ref="spouseBean"/> Tuesday, June 11, 13
  • 21. 20 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 Tuesday, June 11, 13
  • 22. 20 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 Tuesday, June 11, 13
  • 23. 20 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 Tuesday, June 11, 13
  • 24. 20 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 Tuesday, June 11, 13
  • 25. 20 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 § Specific cache setup per environment – through profiles? • potentially even adapting to a runtime-provided service Tuesday, June 11, 13
  • 26. 20 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 § Specific cache setup per environment – through profiles? • potentially even adapting to a runtime-provided service @Cacheable ( name = “owner”) public Owner loadOwner(int id); Tuesday, June 11, 13
  • 27. 20 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 § Specific cache setup per environment – through profiles? • potentially even adapting to a runtime-provided service @Cacheable ( name = “owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") Tuesday, June 11, 13
  • 28. 20 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 § Specific cache setup per environment – through profiles? • potentially even adapting to a runtime-provided service @Cacheable ( name = “owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") public Owner loadOwner(String name); Tuesday, June 11, 13
  • 29. 20 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 § Specific cache setup per environment – through profiles? • potentially even adapting to a runtime-provided service @Cacheable ( name = “owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") public Owner loadOwner(String name); @CacheEvict (name = “owners”) Tuesday, June 11, 13
  • 30. 20 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 § Specific cache setup per environment – through profiles? • potentially even adapting to a runtime-provided service @Cacheable ( name = “owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") public Owner loadOwner(String name); @CacheEvict (name = “owners”) public void deleteOwner(int id); Tuesday, June 11, 13
  • 31. 21 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.0's ServletContainerInitializer mechanism • in combination with Spring 3.1's AnnotationConfigWebApplicationContext • plus Spring 3.1's environment abstraction § Exposure of native Servlet 3.0 functionality in Spring MVC • standard Servlet 3.0 file upload behind Spring's MultipartResolver abstraction • support for asynchronous request processing coming in Spring 3.2 Tuesday, June 11, 13
  • 32. 22 WebApplicationInitializer Example /** Automatically detected and invoked on startup by Spring's ServletContainerInitializer. May register listeners, filters, servlets etc against the given Servlet 3.0 ServletContext. */ public class MyApplicationWebApplicationInitializer implements WebApplicationInitializer { public void onStartup(ServletContext sc) throws ServletException { // create ‘root’ Spring ApplicationContext AnnotationConfigWebApplicationContext root = root AnnotationConfigWebApplicationContext(); root.scan("com.mycompany.myapp"); root.register(FurtherConfig.class); // Manages the lifecycle of the root application context sc.addListener(new ContextLoaderListener(root)); } } Tuesday, June 11, 13
  • 33. 23 @MVC Processing & Flash Attributes Tuesday, June 11, 13
  • 34. 23 @MVC Processing & Flash Attributes § RequestMethodHandlerAdapter l arbitrary mappings to handler methods across multiple controllers l better customization of handler method arguments − HandlerMethodArgumentResolver − HandlerMethodReturnValueHandler − etc Tuesday, June 11, 13
  • 35. 23 @MVC Processing & Flash Attributes § RequestMethodHandlerAdapter l arbitrary mappings to handler methods across multiple controllers l better customization of handler method arguments − HandlerMethodArgumentResolver − HandlerMethodReturnValueHandler − etc § FlashMap support and FlashMapManager abstraction l with RedirectAttributes as a new @MVC handler method argument type − explicitly calling addFlashAttribute to add values to the output FlashMap l an outgoing FlashMap will temporarily get added to the user's session l an incoming FlashMap for a request will automatically get exposed to the model Tuesday, June 11, 13
  • 38. Change of Plans § We originally meant to have Java SE 8 and Java EE 7 themes in Spring 3.2 § However, Java EE 7 got pushed out further and further: Q2 2013 • eventually descoped and delayed (no cloud focus anymore) § And Java SE 8 (OpenJDK 8) got rescheduled as well: September 2013 Q1 2014 • once again, descoped and delayed (no module system anymore) • feature-complete developer preview expected for February 2013 § Our solution: Spring 3.2 ships in Q4 2012 with core framework refinements • Spring 3.3 will ship in Q4 2013 with Java SE 8 and Java EE 7 support. 26 Tuesday, June 11, 13
  • 39. So what’s in 3.2? § Gradle-based build § Binaries built against Java 7 § Inlined ASM 4.0 and CGLIB 3.0 § Async MVC processing on Servlet 3.0 § Spring MVC test support § MVC configuration refinements § SpEL refinements § Also including many runtime refinements • partially back-ported to 3.1.2/3.1.3 § General Spring MVC niceties • Servlet 3 async support • error reporting in REST scenarios • content negotiation strategies • matrix variables 27 Tuesday, June 11, 13
  • 40. Async MVC Processing: Callable 28 @RequestMapping(name =“/upload”, method=RequestMethod.POST) public Callable<String> processUpload(MultipartFile file) { return new Callable<String>() { public String call() throws Exception { // ... return "someView"; } }; } - thread managed by Spring MVC - good for long running database jobs, 3rd party REST API calls, etc Tuesday, June 11, 13
  • 41. Async MVC Processing: DeferredResult 29 @RequestMapping("/quotes") @ResponseBody public DeferredResult quotes() { DeferredResult deferredResult = new DeferredResult(); // Add deferredResult to a Queue or a Map... return deferredResult; } // In some other thread: // Set the return value on the DeferredResult deferredResult.set(data); - thread managed outside of Spring MVC - JMS or AMQP message listener, another HTTP request, etc. Tuesday, June 11, 13
  • 42. Async MVC Processing: AsyncTask 30 @RequestMapping(name =“/upload”, method=RequestMethod.POST) public AsyncTask<Foo> processUpload(MultipartFile file) { TaskExecutor asyncTaskExecutor = new AsyncTaskExecutor(...); return new AsyncTask<Foo>( 1000L, // timeout asyncTaskExecutor, // thread pool new Callable<Foo>(){ ..} // thread ); } - same as Callable, with extra features - override timeout value for async processing - lets you specify a specific AsyncTaskExecutor Tuesday, June 11, 13
  • 43. Content Negotiation Strategies 31 ContentNegotiationStrategy • By 'Accept' Header • By URL extension (.xml, .json, etc) • By Request parameter, i.e. /accounts/1?format=json • Fixed content type, i.e. a fallback option ContentNegotiationManager • has one or more ContentNegotiationStrategy instances • works with: RequestMappingHandlerMapping, RequestMappingHandlerAdapter, ExceptionHandlerExceptionResolver ContentNegotiatingViewResolver Tuesday, June 11, 13
  • 44. Matrix Variables 32 "Each path segment may include a sequence of parameters, indicated by the semicolon ";" character. The parameters are not significant to the parsing of relativeb references. RFC 2396, section 3.3 Tuesday, June 11, 13
  • 45. Matrix Variables 33 "The semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes." RFC 3986, section 3.3 Tuesday, June 11, 13
  • 46. Matrix Variables § Two Types of Usages § Path Segment Name-Value Pairs § As delimited list path segment 34 /qa-releases;buildNumber=135;revision=3.2 /answers/id1;id2;id3;id4/comments Tuesday, June 11, 13
  • 47. Matrix Variables: the common case 35 // GET /pets/42;q=11;r=22 @RequestMapping(value = "/pets/{petId}") public void findPet( @PathVariable String petId, @MatrixVariable int q) { // petId == 42 // q == 11 } Tuesday, June 11, 13
  • 48. Matrix Variables: obtain all matrix variables 36 // GET /owners/42;q=11;r=12/pets/21;q=22;s=23 @RequestMapping(value = "/owners/{ownerId}/pets/{petId}") public void findPet( @MatrixVariable Map<String, String> matrixVars) { // matrixVars: ["q" : [11,22], "r" : 12, "s" : 23] } Tuesday, June 11, 13
  • 49. Matrix Variables: qualify path segment 37 // GET /owners/42;q=11/pets/21;q=22 @RequestMapping(value = "/owners/{ownerId}/pets/{petId}") public void findPet( @MatrixVariable(value="q", pathVar="ownerId") int q1, @MatrixVariable(value="q", pathVar="petId") int q2) { // q1 == 11 // q2 == 22 } Tuesday, June 11, 13
  • 50. 38 MVC Test Framework Server import ... MockMvcBuilders.* ; import ... MockMvcRequestBuilders.*; import ... MockMvcResultMatchers.*; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration("servlet-context.xml") public class SampleTests {     @Autowired   private WebApplicationContext wac;     private MockMvc mockMvc;     @Before   public void setup() {     this.mockMvc = webAppContextSetup(this.wac).build();   }     @Test   public void getFoo() throws Exception {     this.mockMvc.perform(get("/foo").accept("application/json"))         .andExpect(status().isOk())         .andExpect(content().mimeType("application/json"))         .andExpect(jsonPath("$.name").value("Lee"));   } } Tuesday, June 11, 13
  • 51. 39 MVC Test Framework Client RestTemplate restTemplate = new RestTemplate(); MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);   mockServer.expect(requestTo("/greeting"))   .andRespond(withSuccess("Hello world", "text/plain"));   // use RestTemplate ...   mockServer.verify(); Tuesday, June 11, 13
  • 53. Spring Framework 4 (Q4 2013) § Comprehensive Java 8 support • Support for Java EE 7 API levels • Focus on message-oriented architectures • annotation-driven JMS endpoint model § revised application event mechanism § WebSocket support in Spring MVC § Next-generation Groovy support § Grails bean builder finally making it into Spring proper 41 Tuesday, June 11, 13
  • 54. 42 § you can follow along at home.. Spring Framework 4 (Q4 2013) Tuesday, June 11, 13
  • 55. The Java SE 8 and Java EE 7 Story § Comprehensive Java 8 support • lambda expressions a.k.a. closures • Date and Time API (JSR-310) • NIO-based HTTP client APIs • parameter name discovery • java.util.concurrent enhancements § Support for Java EE 7 API levels • JCache 1.0 • JMS 2.0 • JPA2.1 • JTA 1.2 (@Transactional) • Bean Validation 1.1 • Servlet3.1 • JSF 2.2 43 § Retaining support for Java 5 and higher • with Java 6 and 7 as common levels • Java 8 potentially becoming popular rather quickly... Tuesday, June 11, 13
  • 56. Resource Caching § expanding mvc:resources § Support for pre-processing resources § Might look similar to the Grails resource pipeline 44 Tuesday, June 11, 13
  • 57. Groovy Support § Groovy BeanBuilder might make it into Spring 4 core § Enhanced language level support 45 Tuesday, June 11, 13
  • 58. @Conditional 46 @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface Conditional { /** * All {@link Condition}s that must {@linkplain Condition#matches match} in order for * the component to be registered. */ Class<? extends Condition>[] value(); } public interface Condition { /** * Determine if the condition matches. * @param context the condition context * @param metadata meta-data of the {@link AnnotationMetadata class} or * {@link MethodMethod method} being checked. * @return {@code true} if the condition matches and the component can be registered * or {@code false} to veto registration. */ boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata); } Tuesday, June 11, 13
  • 59. JDK 8 Support In-Depth § implicit use of LinkedHash{Map|Set} instead of HashMap/Set to preserver ordering diffs in JDK 7 and JDK 8 § Embed ASM 4.1 into Spring codebase to support JDK8 bytecode changes and to keep compatability cglib 3.0 § JDK 8 Date and Time (JSR 310) § add awatTerminationSeconds / commonPool properties to ForkJoinPoolFactoryBean to support JDK 8 changes § Incorporate JDK 8 reflection support (java.lang.reflect.Parameter) 47 Tuesday, June 11, 13
  • 60. JMS 2.0 Support 48 <jms:annotation-driven> @JmsListener(destination="myQueue") public void handleMessage(TextMessage payload); @JmsListener(destination="myQueue", selector="...") public void handleMessage(String payload); @JmsListener(destination="myQueue") public String handleMessage(String payload); Tuesday, June 11, 13
  • 61. Bean Validation 1.1 Support in Spring 49 § now works with Hibernate Validator 5 § MethodValidationInterceptor auto-detects Bean Validation 1.1's ExecutableValidator API now and uses it in favor of Hibernate Validator 4.2's native variant. Tuesday, June 11, 13
  • 62. JSR 236 (ManagedExecutorService) support 50 • ConcurrentTask(Executor|Scheduler) now automatically detect a JSR 236 ManagedExecutorService and adapt them Tuesday, June 11, 13
  • 63. • simplest case: let JSR 356 scan for your endpoint • drawback: scanning takes a long time Web Sockets Support (JSR-356) - Servlet scanning 51 import javax.websocket.server.ServerEndpoint; import org.springframework.web.socket.server.endpoint. SpringConfigurator.  @ServerEndpoint(value = "/echo", configurator = SpringConfigurator.class) public class EchoEndpoint {     private final EchoService echoService;     @Autowired   public EchoEndpoint(EchoService echoService) {     this.echoService = echoService;   }     @OnMessage   public void handleMessage(Session session, String message) {     // ...   }   } Tuesday, June 11, 13
  • 64. Web Sockets Support (JSR-356) - Spring container-centric registration (you can turn off scan) 52 import org.springframework.web.socket.server.endpoint.ServerEndpointExporter; import org.springframework.web.socket.server.endpoint.ServerEndpointRegistration;   @Configuration public class EndpointConfig { @Bean public EchoService service(){ ... }     @Bean   public EchoEndpoint echoEndpoint(EchoService service) {     return new EchoEndpoint(service );   }   // once per application   @Bean   public ServerEndpointExporter endpointExporter() {     return new ServerEndpointExporter();   }    } Tuesday, June 11, 13
  • 65. import org.springframework.web.socket.server.endpoint.ServerEndpointExporter; import org.springframework.web.socket.server.endpoint.ServerEndpointRegistration;   @Configuration public class EndpointConfig { @Bean public EchoService service(){ ... }   @Bean public EchoEndpoint endpoint(EchoService service) { return new EchoEndpoint( service ); }   @Bean  public EndpointRegistration echoEndpointRegistration (EchoEndpoint eep ) {     return new EndpointRegistration(“/echo”, eep );   }   // once per application   @Bean   public ServerEndpointExporter endpointExporter() {     return new ServerEndpointExporter();   } } Web Sockets Support (JSR-356) - Spring container-centric registration (you can turn off scan) endpoint class endpoint instance instance per socket Spring scope Tuesday, June 11, 13
  • 66. Web Sockets Support (Spring Web Sockets Abstraction) 54 § rooted in org.springframework.web.socket § not meant to be consumed directly, too low level. § A good practice is one handler (and one web socket) per application. § You’d have to handle all requests with one class and handler. § (Imagine REST without verbs, too limited!) § This begs for a higher level API with annotations. § Basis for other support, including SockJS § More flexible API, first (and likely permanent) implementation based on Jetty 9 § implementation based on Jetty 9 § API rooted at WebSocketHandler Tuesday, June 11, 13
  • 67. import org.springframework.web.socket.adapter.TextWebSocketHandlerAdapter;   public class EchoHandler extends TextWebSocketHandlerAdapter {     @Override   public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {     session.sendMessage(message);   }   } Web Sockets Support (Spring Web Sockets Abstraction - WebSocketHandler) Tuesday, June 11, 13
  • 68. import org.springframework.web.socket.server.support. WebSocketHttpRequestHandler;   @Configuration public class WebConfig { @Bean public EchoHandler handler(){ ... }     @Bean   public SimpleUrlHandlerMapping handlerMapping(EchoHandler handler ) {       Map<String, Object> urlMap = new HashMap<String, Object>();     urlMap.put("/echo", new WebSocketHttpRequestHandler( handler ));       SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping();     hm.setUrlMap(urlMap);     return hm;   }   } Web Sockets Support (Spring Web Sockets Abstraction - WebSocketHandler) Tuesday, June 11, 13
  • 69. import org.springframework.web.socket.sockjs.SockJsService; // ...   @Configuration public class WebConfig {     @Bean   public SimpleUrlHandlerMapping handlerMapping( EchoHandler handler, TaskScheduler ts ) {       SockJsService sockJsService = new DefaultSockJsService( ts );       Map<String, Object> urlMap = new HashMap<String, Object>();     urlMap.put("/echo/**", new SockJsHttpRequestHandler(sockJsService, handler ));       SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping();     hm.setUrlMap(urlMap);     return hm;   }     @Bean  public TaskScheduler taskScheduler() { ... }   } Web Sockets Support (Spring Web Sockets Abstraction - SockJS) Tuesday, June 11, 13
  • 70. import org.springframework.web.socket.client.endpoint.AnnotatedEndpointConnectionManager;   @Configuration public class EndpointConfig {     // For Endpoint sub-classes use EndpointConnectionManager instead     @Bean   public AnnotatedEndpointConnectionManager connectionManager(EchoEndpoint endpoint) {     return new AnnotatedEndpointConnectionManager( endpoint, "ws://localhost:8080/webapp/echo");   }     @Bean   public EchoEndpoint echoEndpoint() {     // ...   }   } Web Sockets Support (client side) Tuesday, June 11, 13
  • 71. JMS 2.0 Support 59 • Added "deliveryDelay" property on JmsTemplate • Added support for "deliveryDelay" and CompletionListener to CachedMessageProducer • Added support for the new "create(Shared)DurableConsumer" variants in Spring’s CachingConnectionFactory • Added support for the new "createSession" variants with fewer parameters in Spring’s SingleConnectionFactory Tuesday, June 11, 13
  • 72. Current and Upcoming: 3.1, 3.2, and 3.2 § Spring Framework 3.1 (Dec 2011) • Environment profiles, Java-based configuration, declarative caching • Initial Java 7 support, Servlet 3.0 based deployment § Spring Framework 3.2 (Dec 2012) • Gradle-based build, GitHub-based contribution model • Fully Java 7 oriented, async MVC processing on Servlet 3.0 § Spring Framework 3.3 (Q4 2013) • Comprehensive Java SE 8 support (including lambda expressions) • Support for Java EE 7 API level and WebSockets 60 Tuesday, June 11, 13
  • 73. NOT CONFIDENTIAL -- TELL EVERYONE @SpringSource @Starbuxman Questions? Tuesday, June 11, 13