SlideShare uma empresa Scribd logo
1 de 73
© 2013 SpringSource, by VMware
The Spring Update
Josh Long (⻰龙之春)
@starbuxman
joshlong.com
josh.long@springsource.com
slideshare.net/joshlong
Wednesday, June 5, 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
Wednesday, June 5, 13
Josh Long (⻰龙之春)
@starbuxman
joshlong.com
josh.long@springsource.com
slideshare.net/joshlong
Contributor To:
•Spring Integration
•Spring Batch
•Spring Hadoop
•Activiti Workflow Engine
Wednesday, June 5, 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
Wednesday, June 5, 13
Spring 3.1
5
Wednesday, June 5, 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
Wednesday, June 5, 13
Not confidential. Tell everyone.
So, What’s All of This Look Like in Code?
7
Wednesday, June 5, 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){
...
}
}
Wednesday, June 5, 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;
}
}
Wednesday, June 5, 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;
}
}
Wednesday, June 5, 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) {
...
}
...
}
Wednesday, June 5, 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 );
}
...
}
Wednesday, June 5, 13
Not confidential. Tell everyone.
...But Where’d the SessionFactory come from?
13
Wednesday, June 5, 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” );
Wednesday, June 5, 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 );
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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() {
...
}
}
Wednesday, June 5, 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"/>
Wednesday, June 5, 13
20
Cache Abstraction
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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);
Wednesday, June 5, 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")
Wednesday, June 5, 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);
Wednesday, June 5, 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”)
Wednesday, June 5, 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);
Wednesday, June 5, 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
Wednesday, June 5, 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));
}
}
Wednesday, June 5, 13
23
@MVC Processing & Flash Attributes
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 13
github.com/SpringSource
24
Wednesday, June 5, 13
Spring 3.2
25
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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.
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 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
}
Wednesday, June 5, 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]
}
Wednesday, June 5, 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
}
Wednesday, June 5, 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"));
  }
}
Wednesday, June 5, 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();
Wednesday, June 5, 13
Spring 4
40
Wednesday, June 5, 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
Wednesday, June 5, 13
42
§ you can follow along at home..
Spring Framework 4 (Q4 2013)
Wednesday, June 5, 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...
Wednesday, June 5, 13
Resource Caching
§ expanding mvc:resources
§ Support for pre-processing resources
§ Might look similar to the Grails resource pipeline
44
Wednesday, June 5, 13
Groovy Support
§ Groovy BeanBuilder might make it into Spring 4 core
§ Enhanced language level support
45
Wednesday, June 5, 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);
}
Wednesday, June 5, 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
Wednesday, June 5, 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);
Wednesday, June 5, 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.
Wednesday, June 5, 13
JSR 236 (ManagedExecutorService) support
50
• ConcurrentTask(Executor|Scheduler) now automatically detect a
JSR 236 ManagedExecutorService and adapt them
Wednesday, June 5, 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) {
    // ...
  }
 
}
Wednesday, June 5, 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();
  }
  
}
Wednesday, June 5, 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 (EchoEndpointRegistration 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
Wednesday, June 5, 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
Wednesday, June 5, 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)
Wednesday, June 5, 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)
Wednesday, June 5, 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)
Wednesday, June 5, 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)
Wednesday, June 5, 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
Wednesday, June 5, 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
Wednesday, June 5, 13
NOT CONFIDENTIAL -- TELL EVERYONE
@SpringSource @Starbuxman
Questions?
Wednesday, June 5, 13

Mais conteúdo relacionado

Mais procurados

High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016Vlad Mihalcea
 
Vs2010and Ne Tframework
Vs2010and Ne TframeworkVs2010and Ne Tframework
Vs2010and Ne TframeworkKulveerSingh
 
Plmce2015 java 101 - david bennett
Plmce2015   java 101 - david bennettPlmce2015   java 101 - david bennett
Plmce2015 java 101 - david bennettDavid Bennett
 
Hostingultraso australia
Hostingultraso australiaHostingultraso australia
Hostingultraso australiavinodkinoni
 
How to Make AJAX Applications Scream on the Client
How to Make AJAX Applications Scream on the ClientHow to Make AJAX Applications Scream on the Client
How to Make AJAX Applications Scream on the Clientgoodfriday
 
Getting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationGetting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationPhilip Norton
 
MySQL 8.0.19 - New Features Summary
MySQL 8.0.19 - New Features SummaryMySQL 8.0.19 - New Features Summary
MySQL 8.0.19 - New Features SummaryOlivier DASINI
 
10x Performance Improvements - A Case Study
10x Performance Improvements - A Case Study10x Performance Improvements - A Case Study
10x Performance Improvements - A Case StudyRonald Bradford
 
Scaling Twitter 12758
Scaling Twitter 12758Scaling Twitter 12758
Scaling Twitter 12758davidblum
 
Drupal 8 Configuration Management
Drupal 8 Configuration ManagementDrupal 8 Configuration Management
Drupal 8 Configuration ManagementPhilip Norton
 
DATABASE AUTOMATION with Thousands of database, monitoring and backup
DATABASE AUTOMATION with Thousands of database, monitoring and backupDATABASE AUTOMATION with Thousands of database, monitoring and backup
DATABASE AUTOMATION with Thousands of database, monitoring and backupSaewoong Lee
 
Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)
Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)
Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)Nuvole
 
Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)
Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)
Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)Nuvole
 
Feed Burner Scalability
Feed Burner ScalabilityFeed Burner Scalability
Feed Burner Scalabilitydidip
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Power of Simplicity in FW/1
Power of Simplicity in FW/1Power of Simplicity in FW/1
Power of Simplicity in FW/1Masha Edelen
 

Mais procurados (20)

High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016High Performance Hibernate JavaZone 2016
High Performance Hibernate JavaZone 2016
 
Vs2010and Ne Tframework
Vs2010and Ne TframeworkVs2010and Ne Tframework
Vs2010and Ne Tframework
 
Plmce2015 java 101 - david bennett
Plmce2015   java 101 - david bennettPlmce2015   java 101 - david bennett
Plmce2015 java 101 - david bennett
 
Spring.io
Spring.ioSpring.io
Spring.io
 
Hostingultraso australia
Hostingultraso australiaHostingultraso australia
Hostingultraso australia
 
My sql tutorial-oscon-2012
My sql tutorial-oscon-2012My sql tutorial-oscon-2012
My sql tutorial-oscon-2012
 
How to Make AJAX Applications Scream on the Client
How to Make AJAX Applications Scream on the ClientHow to Make AJAX Applications Scream on the Client
How to Make AJAX Applications Scream on the Client
 
Getting Into Drupal 8 Configuration
Getting Into Drupal 8 ConfigurationGetting Into Drupal 8 Configuration
Getting Into Drupal 8 Configuration
 
MySQL 8.0.19 - New Features Summary
MySQL 8.0.19 - New Features SummaryMySQL 8.0.19 - New Features Summary
MySQL 8.0.19 - New Features Summary
 
10x Performance Improvements - A Case Study
10x Performance Improvements - A Case Study10x Performance Improvements - A Case Study
10x Performance Improvements - A Case Study
 
Scaling Twitter 12758
Scaling Twitter 12758Scaling Twitter 12758
Scaling Twitter 12758
 
Drupal 8 Configuration Management
Drupal 8 Configuration ManagementDrupal 8 Configuration Management
Drupal 8 Configuration Management
 
MyBatis
MyBatisMyBatis
MyBatis
 
DATABASE AUTOMATION with Thousands of database, monitoring and backup
DATABASE AUTOMATION with Thousands of database, monitoring and backupDATABASE AUTOMATION with Thousands of database, monitoring and backup
DATABASE AUTOMATION with Thousands of database, monitoring and backup
 
Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)
Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)
Configuration Management in Drupal 8: A preview (DrupalDays Milano 2014)
 
Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)
Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)
Configuration Management in Drupal 8: A preview (DrupalCamp Alpe Adria 2014)
 
Feed Burner Scalability
Feed Burner ScalabilityFeed Burner Scalability
Feed Burner Scalability
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Power of Simplicity in FW/1
Power of Simplicity in FW/1Power of Simplicity in FW/1
Power of Simplicity in FW/1
 

Destaque

Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta jaxconf
 
Building an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen TingBuilding an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen Tingjaxconf
 
What you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie AllenWhat you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie Allenjaxconf
 
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin HerbasThe New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbasjaxconf
 
Future of the Web - Yehuda Katz
Future of the Web - Yehuda KatzFuture of the Web - Yehuda Katz
Future of the Web - Yehuda Katzjaxconf
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remanijaxconf
 
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
 
Java PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao KandJava PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao Kandjaxconf
 
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu BariApache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu Barijaxconf
 
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...jaxconf
 
JSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian HlavatsJSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian Hlavatsjaxconf
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargentajaxconf
 
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...jaxconf
 
The Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun SmithThe Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun Smithjaxconf
 
From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEjaxconf
 

Destaque (15)

Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
 
Building an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen TingBuilding an Impenetrable ZooKeeper - Kathleen Ting
Building an Impenetrable ZooKeeper - Kathleen Ting
 
What you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie AllenWhat you need to know about Lambdas - Jamie Allen
What you need to know about Lambdas - Jamie Allen
 
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin HerbasThe New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
The New Reality: the Role of PaaS in Technology Innovation - Franklin Herbas
 
Future of the Web - Yehuda Katz
Future of the Web - Yehuda KatzFuture of the Web - Yehuda Katz
Future of the Web - Yehuda Katz
 
The economies of scaling software - Abdel Remani
The economies of scaling software - Abdel RemaniThe economies of scaling software - Abdel Remani
The economies of scaling software - Abdel Remani
 
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
 
Java PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao KandJava PaaS Comparisons - Khanderao Kand
Java PaaS Comparisons - Khanderao Kand
 
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu BariApache Hadoop and its role in Big Data architecture - Himanshu Bari
Apache Hadoop and its role in Big Data architecture - Himanshu Bari
 
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
Vaadin, Rich Web Apps in Server-Side Java without Plug-ins or JavaScript: Joo...
 
JSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian HlavatsJSF2 Composite Components - Ian Hlavats
JSF2 Composite Components - Ian Hlavats
 
Architecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko GargentaArchitecting Android Apps: Marko Gargenta
Architecting Android Apps: Marko Gargenta
 
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
MVC on the Server and on the Client: How to Integrate Spring MVC and Backbone...
 
The Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun SmithThe Evolution of Java Persistence in EclipseLink: Shaun Smith
The Evolution of Java Persistence in EclipseLink: Shaun Smith
 
From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEE
 

Semelhante a The Spring 4 Update - Josh Long

the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 updateJoshua Long
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
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
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introductionRasheed Waraich
 
IMC Summit 2016 Breakout - Greg Luck - How to Speed Up Your Application Using...
IMC Summit 2016 Breakout - Greg Luck - How to Speed Up Your Application Using...IMC Summit 2016 Breakout - Greg Luck - How to Speed Up Your Application Using...
IMC Summit 2016 Breakout - Greg Luck - How to Speed Up Your Application Using...In-Memory Computing Summit
 
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
 
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
 
Caching and JCache with Greg Luck 18.02.16
Caching and JCache with Greg Luck 18.02.16Caching and JCache with Greg Luck 18.02.16
Caching and JCache with Greg Luck 18.02.16Comsysto Reply GmbH
 
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...HostedbyConfluent
 
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
 
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
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Gunith Devasurendra
 
What’s New in Spring Batch?
What’s New in Spring Batch?What’s New in Spring Batch?
What’s New in Spring Batch?VMware Tanzu
 
The new static resources framework
The new static resources frameworkThe new static resources framework
The new static resources frameworkmarcplmer
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfAppster1
 

Semelhante a The Spring 4 Update - Josh Long (20)

the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
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 boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
IMC Summit 2016 Breakout - Greg Luck - How to Speed Up Your Application Using...
IMC Summit 2016 Breakout - Greg Luck - How to Speed Up Your Application Using...IMC Summit 2016 Breakout - Greg Luck - How to Speed Up Your Application Using...
IMC Summit 2016 Breakout - Greg Luck - How to Speed Up Your Application Using...
 
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
 
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
 
Caching and JCache with Greg Luck 18.02.16
Caching and JCache with Greg Luck 18.02.16Caching and JCache with Greg Luck 18.02.16
Caching and JCache with Greg Luck 18.02.16
 
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
Developing Kafka Streams Applications with Upgradability in Mind with Neil Bu...
 
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
 
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
 
Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)Rediscovering Spring with Spring Boot(1)
Rediscovering Spring with Spring Boot(1)
 
What’s New in Spring Batch?
What’s New in Spring Batch?What’s New in Spring Batch?
What’s New in Spring Batch?
 
The new static resources framework
The new static resources frameworkThe new static resources framework
The new static resources framework
 
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdfdokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
dokumen.tips_rediscovering-spring-with-spring-boot1 (1).pdf
 

Último

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 

Último (20)

Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
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
 
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
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 

The Spring 4 Update - Josh Long

  • 1. © 2013 SpringSource, by VMware The Spring Update Josh Long (⻰龙之春) @starbuxman joshlong.com josh.long@springsource.com slideshare.net/joshlong Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 13
  • 7. Not confidential. Tell everyone. So, What’s All of This Look Like in Code? 7 Wednesday, June 5, 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){ ... } } Wednesday, June 5, 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; } } Wednesday, June 5, 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; } } Wednesday, June 5, 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) { ... } ... } Wednesday, June 5, 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 ); } ... } Wednesday, June 5, 13
  • 13. Not confidential. Tell everyone. ...But Where’d the SessionFactory come from? 13 Wednesday, June 5, 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” ); Wednesday, June 5, 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 ); Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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() { ... } } Wednesday, June 5, 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"/> Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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); Wednesday, June 5, 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") Wednesday, June 5, 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); Wednesday, June 5, 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”) Wednesday, June 5, 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); Wednesday, June 5, 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 Wednesday, June 5, 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)); } } Wednesday, June 5, 13
  • 33. 23 @MVC Processing & Flash Attributes Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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. Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 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 } Wednesday, June 5, 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] } Wednesday, June 5, 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 } Wednesday, June 5, 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"));   } } Wednesday, June 5, 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(); Wednesday, June 5, 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 Wednesday, June 5, 13
  • 54. 42 § you can follow along at home.. Spring Framework 4 (Q4 2013) Wednesday, June 5, 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... Wednesday, June 5, 13
  • 56. Resource Caching § expanding mvc:resources § Support for pre-processing resources § Might look similar to the Grails resource pipeline 44 Wednesday, June 5, 13
  • 57. Groovy Support § Groovy BeanBuilder might make it into Spring 4 core § Enhanced language level support 45 Wednesday, June 5, 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); } Wednesday, June 5, 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 Wednesday, June 5, 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); Wednesday, June 5, 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. Wednesday, June 5, 13
  • 62. JSR 236 (ManagedExecutorService) support 50 • ConcurrentTask(Executor|Scheduler) now automatically detect a JSR 236 ManagedExecutorService and adapt them Wednesday, June 5, 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) {     // ...   }   } Wednesday, June 5, 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();   }    } Wednesday, June 5, 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 (EchoEndpointRegistration 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 Wednesday, June 5, 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 Wednesday, June 5, 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) Wednesday, June 5, 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) Wednesday, June 5, 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) Wednesday, June 5, 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) Wednesday, June 5, 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 Wednesday, June 5, 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 Wednesday, June 5, 13
  • 73. NOT CONFIDENTIAL -- TELL EVERYONE @SpringSource @Starbuxman Questions? Wednesday, June 5, 13