public
Last active

This is a complete working Spring MVC REST application. The only thing unspecified are the imports and the Maven pom.xml. Deploy this class as a .war using Spring MVC 3.2.x (and, specifically, the spring-webmvc library) and you're done!

  • Download Gist
MvcRestApplicationInitializer.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/**
* <p>This will be picked up in a Servlet 3 environment like Apache Tomcat 7.
*
* <p>This replaces <code>web.xml</code>.
*
*/
public class MvcRestApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override protected Class<?> [] getRootConfigClasses() {
return new Class<?>[]{};
}
@Override protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{ RestConfiguration.class };
}
@Override protected String[] getServletMappings(){ return new String[]{"/"}; }
}
/**
* Installs Spring MVC and all the required support for JSON assuming
* Jackson's on the CLASSPATH
*/
@EnableWebMvc
@ComponentScan
@Configuration
class RestConfiguration {
// that's all!
}
/**
* A simple Spring MVC REST controller. The returned value (Customer) will
* be converted into JSON if the client signals that it can read JSON (using the
* <CODE>ACCEPT</CODE> header.)
*/
@Controller
class StatusController {
@RequestMapping(value= "/customers/{customerId}", method= RequestMethod.GET)
public @ResponseBody Customer loadCustomer(@PathVariable long customerId ) {
// return a POJO Customer somehow (perhaps look it up in a database?)
return someCustomer ;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.