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?
@Configuration. Treat as the configuration file for Spring MVC-enabled applications. Also, we use the @Bean tag to register ViewResolver. We use InternalResourceViewResolver.
The @RequestMapping annotation can be applied to class-level and/or method-level in a controller. The class-level annotation maps a specific request path or pattern onto a controller. You can then apply additional method-level annotations to make mappings more specific to handler methods.
What is Spring Annotation Based Configuration? In Spring Framework annotation-based configuration instead of using XML for describing the bean wiring, you have the choice to move the bean configuration into component class. It is done by using annotations on the relevant class, method or the field declaration.
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/"); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With