Annotation Configuration Replacement for mvc:resources - Spring

Multi tool use
Annotation Configuration Replacement for mvc:resources - Spring
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:
web.xml
<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.
WebApplicationInitializer
@EnableWebMvc
Is there an annotation or new configuration to pull these resources back in without having to use xml?
2 Answers
2
One way to do this is to have your configuration class extend WebMvcConfigurerAdapter
, then override the following method as such:
WebMvcConfigurerAdapter
@Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
thank so much! Saved my life :-)
– kholofelo Maloma
Sep 22 '15 at 8:58
Upvoted for the answer. Better if you can add explanation. That would be nice for a beginner.
– Menuka Ishan
Sep 13 '16 at 10:52
@Menuka Explaination: Every request which begins with "/resources/**" path will be mapped to a files in a "/resources/" folder.
– Krystian
Dec 11 '16 at 13:21
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
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
This answer is totally correct. However, if you're having issues (like I was) after adding this, remember that you might still need a default servlet handler described here: stackoverflow.com/a/17013442/2047962
– RustyTheBoyRobot
Jan 26 '15 at 16:32