Spring MVC 4: Add Static Resources by Annotation

In this article I’ll describe how you can add your Static Resources by Annotations with Spring MVC 4.0.0 instead of using the old fashioned XML configuration approach.

Introduction

First of all I set up a new Spring MVC project using one of the new example projects which you can import with STS (Spring Tool Suite). It is based on the Spring Framework version 4.0 which has been released recently. If you’re used to the XML Configuration approach the new project structure might not look familiar to you. Instead of a XML Configuration file you can use the Annotation @Configuration now to configure all your Servlet settings.

Static Assets

I added an assets directory to my resources directory which is used to store all static assets like CSS, JavaScript and Images. In the next step I added a subdirectory for each asset type and a sample app.js to my /js directory. So my directory structure now looks like this:

  • /resources/assets
    • /css
    • /js
    • /img

If I try to access it in the browser I’ll get a HTTP 404 Error Response (Problem accessing /assets/js/app.js, Reason: Not Found). In the XML configuration file usually we had to add a resource mapping with . So what would be the equivalent to the Annotation Configuration approach?

Add a Resource Handler

The answer is the ResourceHandlerRegistry Class.

Excerpt from the Spring Docs:

Stores registrations of resource handlers for serving static resources such as images,
css files and others through Spring MVC…

Java based Container Configuration

Furthermore we have to add the @Configuration Annotation to our MVC Configuration class. This will enable the Java based Container configuration instead of the XML configuration.

In the next step I added a addResourceHandlers method to my MVC Configuration class which looks like this:

public void addResourceHandlers(ResourceHandlerRegistry registry) {
  registry.addResourceHandler("/assets/**")
    .addResourceLocations("classpath:/assets/");
  registry.addResourceHandler("/css/**")
    .addResourceLocations("/css/");
  registry.addResourceHandler("/img/**")
    .addResourceLocations("/img/");
  registry.addResourceHandler("/js/**")
    .addResourceLocations("/js/");
}

Now can access all your assets from your resources directory in your classpath.

2 Comments

Leave a Comment.