This Week in Spring, June 5th, 2012

Engineering | Josh Long | June 06, 2012 | ...

Welcome back to another installment of This Week in Spring. As usual, we've got a lot to look at this week so let's get to it..

  1. The video from Chris Beams's recent webinar on the various styles of dependency injection that Spring supports is up. Chris is a core Spring framework engineer (and all around good guy). This video is definitely worth a watch especially if you still think Spring configurations requires XML.
    	  </LI> 
     <LI> Oleg Zhurakousky announced the availability of 
    	 <a href = "http://www.springsource.org/node/3569">
    	 Spring Integration 2.1.2 RELEASE and 2.2.0M2</A>. The new releases are filled with many important bug fixes as well as several  
    	
    	 new features.  
    	 </LI>
    	<LI>  Roy Clarkson has announced the availability of <a href= "http://www.springsource.org/spring-android/news/1.0.0-released">Spring Android 1.0.0.RELEASE</A>! The project is an extension of the Spring Framework that aims to simplify the development of native Android applications by providing RESTTemplate support for…

This Week in Spring: May 29th 2012

Engineering | Adam Fitzgerald | May 29, 2012 | ...

Welcome back to another installment of This Week in Spring! As usual, we have a lot to cover, so let's get straight to it!

  1. Chris Beams has announced that the first milestone release towards Spring 3.2 is now available! This release is great!
    	It includes 
    
    	initial support for asynchronous <CODE> @Controller</CODE> methods,
    	early support for JCache-based cache providers,
    	significant performance improvements in autowiring of non-singleton beans,
    	initial delay support for <CODE> @Scheduled</CODE> and <CODE> &lt;task:scheduled&gt;</CODE>,
    	ability to choose between multiple executuors with <CODE>@Async</CODE>,
    	enhanced bean profile selection using the not (<CODE>!</CODE>) operator,  
    	48 bugs fixed, 8 new features and 36 improvements implemented. 
    	
    

    Check out the latest and greatest bits now, and feel free to give feedback!

    When I asked for any items for consideration into this roundup on my Twitter account, one user immediately shot back: "With the Spring 3.2 news, how about a poll on whether the community wants 3.2 M1 to be followed by RC1. It's too good to wait." I agree, this release is

Spring Roo 1.2.2.RELEASE available

Engineering | Alan Stewart | May 28, 2012 | ...

The Spring Roo team is pleased to announce the availability 1.2.2.RELEASE.  This is the second maintenance release for 1.2 and includes fixes for a number of issues and includes support for Spring Framework 3.1.1 and JDK 7.  Roo 1.2.2 also includes the excellent new "tailor" feature provided by our new partner, Accenture.

I hope you enjoy this new release!

Alan

Spring Roo Project Lead

Transactions, Caching and AOP: understanding proxy usage in Spring

Engineering | Michael Isvy | May 23, 2012 | ...

In the Spring framework, many technical features rely on proxy usage. We are going to go in depth on this topic using three examples: Transactions, Caching and Java Configuration.

All the code samples shown in this blog entry are available on my github account.

Transactions

First step: no transaction

The Service class below is not transactional yet. Let’s first look at it as is and then make it become transactional.

@Service
public class AccountServiceImpl  implements AccountService {
 //…

//Not specifying a transaction policy here!
 public void create(Account account) {
 entityManager.persist(account);
 }
}

Since the method “create” is not transactional, it will most likely throw an exception (because this Account object should not…

This Week in Spring - May 22nd, 2012

Engineering | Josh Long | May 22, 2012 | ...

Welcome back to another installment of This Week in Spring. We have a lot of great content this week, as usual!

  1. Rossen Stoyanchev has put up another blog in his series on Spring MVC 3.2 Preview. This latest installment introduces a Spring MVC chat example.
  2. Oliver Gierke has announced the 1.1.0 GA version of Spring Data JPA. Spring Data JPA makes it very simple to build JPA-based repositories, saving you from the tedious boiler plate code. This new release includes new keywords for query generation (LessThanEqual, GreaterThanEqual, Before, After, StartsWith, EndsWith, and Contains), a handy PersistenceUnitPostProcessor to scan for JPA entities (to be used in Spring versions before 3.1), support for native queries in @Query, and support for declarative locking.
  3. Jonathan Brisbin announced the 1.0.0.M2 release of Spring Data REST. Spring Data REST let's you easily export your Spring repository objects as RESTful endpoints. The new release includes support for invoking query methods of Repository interfaces, support for JSR 303 and Spring Validator validations, and improved support for Spring ApplicationEvents that are emitted before and after each save or delete, and annotation-based configuration.
  4. Oleg Zhurakousky has announced the first milestone release of Spring Integration 2.2. This release includes dependency upgrades, JPA support, and support for "publisher confirms and returns," which are newly supported in Spring AMQP.
  5. Gary Russell has announced version 1.1.0 of Spring AMQP that includes support for the RabbitMQ 2.8.x client, which in turn supports mirrored queues, broker failover, publisher confirms, returns, federated exchanges, and much more.
  6. Matt Vickery has a great post introducing the Spring Integration splitter-aggregator pattern.
  7. Willie Wheeler has a great post up on his custom configuration management database (a CMDB). The post details the project, and then talks about his use of Spring Data's repositories in rebuilding the backend for CMDB. Nice post, Willie!
  8. Doug Haber put together a wonderful post on handling paging using Spring Data and the REST support in Spring 3.1.
  9. Blogger panbhatt has a detailed post on using Spring MVC's REST support to solve a particular set of problems he was having.
  10. Blogger OBSERWATORZY described his particular thought process when trying to consume a RESTful service, and wondering if Spring provided an answer (of course it did!). Read on for his resolution.
  11. Vishal Biyani has put together a nice introduction to getting started with Spring Roo and Cloud Foundry.
  12. The RabbitMQ blog has an amazing article introducing queueing theory (with an introduction to throughput, latency and bandwidth.
  13. JAXEnter has a nice roundup of some of the news releases described in this very post, including the Spring AMQP and Spring Data JPA's GAs.

This Week in Spring, May 15th, 2012

Engineering | Josh Long | May 16, 2012 | ...

Welcome back to another installment of This week in Spring!. We've got a lot to cover this week, as usual. So, onward!

  1. Rossen Stoyanchev has just released part two and three of his blog series introducing Spring MVC 3.2's new features. In the first installment, Rossen introduces how to make a Spring MVC @Controller asynchronous. In the second post, Rossen introduces how to add long polling to an existing web application. Long polling is useful in any number of scenarios where you want to simulate server-side push with client-side applications.
  2. <LI>  The video for <a href= "http://blog.springsource.org/author/ozhurakousky/">Oleg Zhurakousky</A>'s followup webinar introducing <a href ="http://www.springsource.org/node/3550">More Practical Tips and Tricks with Spring Integration</A> has just been posted. Check it out! </LI> 
     <LI> <A href ="http://blog.springsource.org/author/rclarkson/">Roy Clarkson</A>  just announced that <a href = "http://www.springsource.org/spring-mobile/news/1.0.0-released">Spring Mobile 1.0.0 has  been released</A>!  </LI>
    
    
    
    <LI>  SpringSource and Cloud Foundry rockstar  <a  href  ="http://blog.springsource…

Spring MVC 3.2 Preview: Chat Sample

Engineering | Rossen Stoyanchev | May 16, 2012 | ...

Last updated on November 5th, 2012 (Spring MVC 3.2 RC1)

In previous blog posts I introduced the Servlet 3 based async capability in Spring MVC 3.2 and used the spring-mvc-showcase and the Spring AMQP stocks sample to demonstrate it. This post presents a chat sample where the external events are not AMQP messages but rather HTTP POST requests with chat messages. In the second part of the post, I'll switch to a distributed chat where the events are Redis notifications.

Chat is not a common requirement for web applications. However it is a good example of a requirement that can only be met with real-time notifications. It is more sensitive to time delays than email or status alerts and it is not that uncommon to chat in a browser with a friend, or with a colleague during a webinar, or with a live person on a shopping site. You can imagine other types of online collaboration.

The Sample

The spring-mvc-chat sample is available on Github. Although not the focus of this blog post, the client side uses Thymeleaf, knockout.js, and jQuery. Thymeleaf is an excellent alternative to JSPs that enables clean HTML templates with support for previews allowing a designer to double-click an HTML template and view it unlike a JSP that requires a Servlet container. knockout.js is a client-side MVC framework that's very handy for attaching behavior to HTML elements. To get an idea about it quickly, follow one of its excellent tutorials. jQuery is used for DOM scripting and Ajax requests.

ChatController

The ChatController exposes operations to get and post chat message. Here is the method to get messages:


@RequestMapping(method=RequestMethod.GET)
@ResponseBody
public DeferredResult<List<String>> getMessages(@RequestParam int messageIndex) {

  final DeferredResult<List<String>> deferredResult = new DeferredResult<List<String>>(null, Collections.emptyList());
  this.chatRequests.put(deferredResult, messageIndex);

  deferredResult.onCompletion(new Runnable() {
    @Override
    public void run() {
      chatRequests.remove(deferredResult);
    }
  });

  List<String> messages = this.chatRepository.getMessages…

Spring MVC 3.2 Preview: Adding Long Polling to an Existing Web Application

Engineering | Rossen Stoyanchev | May 14, 2012 | ...

Last updated on November 5th, 2012 (Spring MVC 3.2 RC1)

In my last post I discussed how to make a Spring MVC controller method asynchronous by returning a Callable which is then invoked in a separate thread by Spring MVC.

But what if async processing depended on receiving some external event in a thread not known to Spring MVC -- e.g. receiving a JMS message, an AMQP message, a Redis pub-sub notification, a Spring Integration event, and so on? I'll explore this scenario by modifying an existing sample from the Spring AMQP project.

The Sample

Spring AMQP has a stock trading sample where a QuoteController sends trade execution messages via Spring AMQP's RabbitTemplate and receives trade confirmation and price quote messages via Spring AMQP's RabbitMQ listener container in message-driven POJO style.

In the browser, the sample uses polling to display price quotes. For trades, the initial request submits the trade and a confirmation id is returned that is then used to poll for the final confirmation. I've updated the sample to take advantage of the Spring 3.2 Servlet 3 async support. The master branch has the code before and the spring-mvc-async branch has the code after the change. The images below show the effect on the frequency of price quote requests (using the Chrome developer tools):

Before the change: traditional polling

After the change: long poll

As you can see with regular polling new requests are sent very frequently (milliseconds apart) while with long polling, requests can be 5, 10, 20, or more seconds apart -- a significant reduction in the total number of requests without the loss of latency, i.e. the amount of time before a new price quote appears in the browser.

Getting Quotes

So what changes were required? From a client perspective traditional polling and long polling are indistinguishable so the HTML and JavaScript did not change. From a server perspective requests must be held up until new quotes arrive. This is how the controller processes a request for quotes:



// Class field
private Map<String, DeferredResult> suspendedTradeRequests = new ConcurrentHashMap<String, DeferredResult>();

...

@RequestMapping("/quotes")
@ResponseBody
public DeferredResult<List<Quote>> quotes(@RequestParam(required = false) Long timestamp) {

  final DeferredResult<List<Quote>> result = new DeferredResult<List<Quote>>(null, Collections.emptyList());
  this.quoteRequests.put(result, timestamp);

  result.onCompletion(new Runnable() {
    public void run() {
      quoteRequests…

Spring MVC 3.2 Preview: Making a Controller Method Asynchronous

Engineering | Rossen Stoyanchev | May 10, 2012 | ...

Last updated on November 5th, 2012 (Spring MVC 3.2 RC1)

In previous posts I introduced the Servlet 3 based async capability in Spring MVC 3.2 and discussed techniques for real-time updates. In this post I'll go into more technical details and discuss how asynchronous processing fits into the Spring MVC request lifecycle.

As a quick reminder, you can make any existing controller method asynchronous by changing it to return a Callable. For example a controller method that returns a view name, can return Callable<String> instead. An @ResponseBody that returns an object called Person can return Callable<Person> instead. And the same is true for any other controller return value type.

A central idea is that all of what you already know about how a controller method works remains unchanged as much as possible except that the remaining processing will occur in another thread. When it comes to asynchronous execution it's important to keep things simple. As you'll see even with this seemingly simple programming model change, there is quite a bit to consider.

The spring-mvc-showcase has been updated for Spring MVC 3.2. Have a look at CallableController. Method annotations like @ResponseBody and @ResponseStatus apply to the return value from the Callable as well, as you might expect. Exceptions raised from a Callable are handled as if they were raised by the controller, in this case with an @ExceptionHandler method. And so on.

If you execute one of the CallableController methods through the "Async Requests" tab in the browser, you should see output similar to the one below:

08:25:15 [http-bio-8080-exec-10] DispatcherServlet - DispatcherServlet with name 'appServlet' processing GET request for [...]
08:25:15 [http-bio-8080-exec-10] RequestMappingHandlerMapping - Looking up handler method for path /async/callable/view
08:25:15 [http-bio-8080-exec-10] RequestMappingHandlerMapping - Returning handler method [...]
08:25:15 [http-bio-8080-exec-10] WebAsyncManager - Concurrent handling starting for GET [...]
08:25:15 [http-bio-8080-exec-10] DispatcherServlet - Leaving response open for concurrent…

Using Cloud Foundry Workers with Spring

Engineering | Josh Long | May 09, 2012 | ...

You've no doubt read Jennifer Hickey's amazing blog posts introducing Cloud Foundry workers, their application in setting up Ruby Resque background jobs, and today's post introducing the Spring support.

Key Takeaways for Spring Developers

  1. You need to update your version of vmc with gem update vmc.
  2. Cloud Foundry workers let you run public static void main jobs. That is, a Cloud Foundry worker is basically a process, lower level than a web application, which maps naturally to many so-called back-office jobs.
  3. You need to provide the command that Cloud Foundry will run. You could provide the java incantation you'd like it to use, but it's far simpler to ship a shell script, and have Cloud Foundry run that shell script for you, instead. The command you provide should employ $JAVA_OPTS, which Cloud Foundry has already provided to ensure consistent memory usage and JVM settings.
  4. There are various ways to automate the creation of a Cloud Foundry deployable application. If you're using Maven, then the org.codehaus.mojo:appassembler-maven-plugin plugin will help you create a startup script and package your .jars for easy deployment, as well as specifying an entry point class.
  5. Everything else is basically the same. When you do vmc push on a Java .jar project, Cloud Foundry will ask you whether the application is a standalone application. Confirm, and it'll walk you through the setup from there.

So, let's look at a few common architectures and arrangements that are easier and more natural with Cloud Foundry workers. We'll look at these patterns in terms of the Spring framework and two surrounding projects, Spring Integration and Spring Batch, both of which thrive in, and outside of, web applications. As we'll see, both of these frameworks support decoupling and improved composability. We'll disconnect what happens from when it happens, and we'll disconnect what happens from where it happens, both in the name of freeing up capacity on the front end.

I've got a Schedule to Keep!

One common question I get is: How do I do job scheduling on Cloud Foundry? Cloud Foundry supports Spring applications, and Spring of course has always supported enterprise grade scheduling abstractions like Quartz and Spring 3.0's @Scheduled annotation. @Scheduled is really nice because it is super easy to add into an existing application. In the simplest case, you add @EnableScheduling to your Java configuration or <task:annotation-driven/> to your XML, and then use the @Scheduled annotation in your code. This is a very natural thing to do in an enterprise application - perhaps you have an analytics or reporting process that needs to run? Some long running batch process? I've put together an example that demonstrates using @Scheduled to run a Spring Batch Job. The Spring Batch job itself is a worker thread that works with a web service whose poor SLA make it unfit for realtime use. It's safer, and cleaner, to handle the work in Spring Batch, where its recovery and retry capabilities pick up the slack of any network outages, network latency, etc. I'll refer you to the code example for most of the details, we'll just look at the the entry point and then look at deploying the application to Cloud Foundry.

					    
// set to every 10s for testing.
@Scheduled(fixedRate = 10 * 1000)
public void runNightlyStockPriceRecorder() throws Throwable {
	JobParameters params = new JobParametersBuilder()
		.addDate("date", new Date())
		.toJobParameters();
	JobExecution jobExecution = jobLauncher.run(job, params);
	BatchStatus batchStatus = jobExecution.getStatus();
	while (batchStatus.isRunning()) {
		logger.info("Still running...");
		Thread.sleep(1000);
	}
	logger.info(String.format("Exit status: %s", jobExecution.getExitStatus().getExitCode()));
	JobInstance jobInstance = jobExecution.getJobInstance…

Get the Spring newsletter

Stay connected with the Spring newsletter

Subscribe

Get ahead

VMware offers training and certification to turbo-charge your progress.

Learn more

Get support

Tanzu Spring offers support and binaries for OpenJDK™, Spring, and Apache Tomcat® in one simple subscription.

Learn more

Upcoming events

Check out all the upcoming events in the Spring community.

View all