Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

<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?

like image 366
Dan W Avatar asked Feb 13 '13 19:02

Dan W


People also ask

What is @configuration in Spring MVC?

@Configuration. Treat as the configuration file for Spring MVC-enabled applications. Also, we use the @Bean tag to register ViewResolver. We use InternalResourceViewResolver.

What is true about @RequestMapping annotation in Spring MVC?

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 annotation based configuration in spring?

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.


2 Answers

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/"); } 
like image 60
AHungerArtist Avatar answered Nov 09 '22 15:11

AHungerArtist


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

like image 45
etech Avatar answered Nov 09 '22 14:11

etech