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.


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) {

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

  • Shalin Singh

    Thanks brother, badly needed this solution.
    Thnaks again.

  • https://twtter.com/lowstz Lowstz Chen

    I migrate my SpringMVC project’s xml config to java config, this article is very clear and save my time.

    Thank you XD.

  • Stephane

    Two more bits of information to add.

    1- Which URL do you type in your browser ?

    2- Is the addResourceHandler parameter the URL one and the addResourceHandler parameter the file system one or vice versa ?

    Thanks !

  • Stephane

    And a third bit:

    3- Does the resources directory sit in the webapp directory ?

  • Petr

    This article is incomplete. You need to extend WebMvcConfigurerAdapter.