Annotation Configuration Replacement for mvc:resources - Spring

JavaSpringSpring MvcConfiguration

Java Problem Overview


I'm trying to upgrade my spring mvc project to utilize the new annotations and get rid of my xml. Previously I was loading my static resources in my web.xml with the line:

<mvc:resources mapping="/resources/**" location="/resources/" /> 

Now, I'm utilizing the WebApplicationInitializer class and @EnableWebMvc annotation to startup my service without any xml files, but can't seem to figure out how to load my resources.

Is there an annotation or new configuration to pull these resources back in without having to use xml?

Java Solutions


Solution 1 - Java

For Spring 3 & 4:

One way to do this is to have your configuration class extend WebMvcConfigurerAdapter, then override the following method as such:

@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}

Solution 2 - Java

Spring 5

As of Spring 5, the correct way to do this is to simply implement the WebMvcConfigurer interface.

For example:

@Configuration
@EnableWebMvc
public class MyApplication implements WebMvcConfigurer {

    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
}

See deprecated message in: WebMvcConfigurerAdapter

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan WView Question on Stackoverflow
Solution 1 - JavaAHungerArtistView Answer on Stackoverflow
Solution 2 - JavaetechView Answer on Stackoverflow