【问题标题】:Annotation Configuration Replacement for mvc:resources - Springmvc:resources 的注解配置替换 - Spring
【发布时间】:2013-01-29 11:33:00
【问题描述】:

我正在尝试升级我的 spring mvc 项目以利用新的注释并摆脱我的 xml。以前我在web.xml 中加载我的静态资源:

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

现在,我正在使用 WebApplicationInitializer 类和 @EnableWebMvc 注释来启动我的服务,而无需任何 xml 文件,但似乎无法弄清楚如何加载我的资源。

是否有注释或新配置可以将这些资源拉回而不必使用 xml?

【问题讨论】:

    标签: java spring spring-mvc configuration


    【解决方案1】:

    春季 3 和 4:

    一种方法是让您的配置类扩展WebMvcConfigurerAdapter,然后重写以下方法:

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

    【讨论】:

    • 这个答案是完全正确的。但是,如果您在添加后遇到问题(就像我一样),请记住您可能仍需要此处描述的默认 servlet 处理程序:stackoverflow.com/a/17013442/2047962
    • 赞成答案。如果你能添加解释就更好了。这对初学者来说会很好。
    • @Menuka 说明:每个以“/resources/**”路径开头的请求都会映射到“/resources/”文件夹中的文件。
    【解决方案2】:

    春天 5

    从 Spring 5 开始,正确的做法是简单地实现 WebMvcConfigurer 接口。

    例如:

    @Configuration
    @EnableWebMvc
    public class MyApplication implements WebMvcConfigurer {
    
        public void addResourceHandlers(final ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        }
    }
    

    查看已弃用的消息:WebMvcConfigurerAdapter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-20
      • 1970-01-01
      相关资源
      最近更新 更多