Enable Web MVC support for your spring app using Java Config

Hello everyone,

This is not a Spring MVC tutorial. I think there are plenty of those on the internet. I just want to show you how you can enable MVC support and create an API for your app.

Sometimes you might have a simple Spring app or even a JSF+Spring web app and want to expose an API. One way to do this is to use Spring MVC Controllers. It takes only 1 minute, I promise.

Let’s see:

1 Register the Spring’s DispatcherServlet in your web.xml :

<!-- Spring servlet -->

You can see there that the url-pattern is set to “/api/*” . Use this only when you want to expose like an API for your app. If you want the dispatcher servlet to intercept all urls then use “/*”

Also you need to set the context config location to point to your java config class (if you don’t have it already):

<!-- @Configuration classes or package -->

2 Now you have to add the EnableWebMvc annotation to your Spring java config class.

VERY IMPORTANT: If your url-pattern is set to something else other than “/*” then you need to customise the request mapping handler mapping. But in order to do this your java config class should extend WebMvcConfigurationSupport. So your spring java config class should look something like this:

@Import({PersistenceJPAConfig.class, AsyncConfig.class, SecurityConfig.class}) // if you want to separate the types of configs
public class AppConfig extends WebMvcConfigurationSupport {
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
        return handlerMapping;

3 Now you have to add the maven dependencies. Dependencies for Spring Web and for Jackson. Spring uses Jackson to send JSON response in the rest call response:


4 That’s pretty much it! Now you can just create a controller using “/api” as root context mapping:

public class MainController implements Serializable {
    private static final long serialVersionUID = 1725889878808740L;
    @RequestMapping(value = "/healthCheck", method = RequestMethod.GET)
    public String healthCheck(Model model) {
        return "Everything is up and running smoothly, sir!";

NOTE: If you use Spring Security then you have to permit access to your new API, otherwise you have to implement some sort of authentication, like basic auth, oauth, simple username and password, simple secret, anything 🙂

If you want to give access to anyone to your api then add this in your spring security java config class:


So, how was it? Fine, you’re right, it took more than 1 minute… maybe 5 tops 🙂

Have fun spreading joy!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s