我想在Windows中使用WebMvcConfigurerAdapter添加资源处理程序,但在Linux中它不起作用,所以我添加WebMvcConfigurationSupport
。
在调试和测试之后,我发现两个bean都将在两个操作系统中创建,但WebMvcConfigurerAdapter
的覆盖功能只能在Windows上执行,而WebMvcConfigurationSupport
的覆盖功能只能在Linux上执行。
我无法找出原因。两个配置类如下所示:
@Configuration
public class JxWebAppConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/src/main/webapp/");
super.addResourceHandlers(registry);
}
}
这是另一个:
@Configuration
public class JxWebConfiguration extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("file:"+System.getProperty("user.dir")+"/src/main/webapp/");
super.addResourceHandlers(registry);
}
}
@EnalbeMvc已在主类
中添加答案 0 :(得分:5)
如上所述in the @EnableWebMvc Documentation:
将此注释添加到@Configuration类可导入Spring WebMvcConfigurationSupport的MVC配置
{..}
要自定义导入的配置,请实现该接口 WebMvcConfigurer或更可能扩展空方法基类 WebMvcConfigurerAdapter并覆盖单个方法
{..}
如果WebMvcConfigurer未公开某些需要的高级设置 要配置,请考虑删除@EnableWebMvc注释和 直接从WebMvcConfigurationSupport
扩展
所以实际上:
@EnableWebMvc
+扩展WebMvcConfigurerAdapter
(建议的第一个选项)WebMvcConfigurationSupport
扩展(完全控制的后备替代方案)(两个案例都需要@Configuration
)
答案 1 :(得分:2)
org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
的替代解决方案是org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport
(我正在使用Spring Framework 5.0.2.RELEASE)。
WebMvcConfigurerAdapter
已被弃用。
答案 2 :(得分:0)
我知道原因。如上所述,您应该选择一个选择(扩展WebMvcConfigurerAdapter+@EnableWebMvc
或仅扩展WebMvcConfigurationSupport
);
永远不要使用@EnableWebMvc
并延长WebMvcConfigurationSupport
一起!!
如果使用spring-boot @EnableAutoConfiguration
,您可以延长WebMvcConfigurerAdapter
并且不使用@EnableMvc
答案 3 :(得分:0)
我不清楚操作系统的性能差异(类路径顺序?),所以我只讨论WebMvcConfigurationSupport
与WebMvcConfigurer
。让我们从实现WebMvcConfigurerAdapter
的{{1}}开始,但是现在不推荐使用,因为该接口具有通过默认方法实现的功能。
现在有了“支持”(扩展WebMvcConfigurer
)和“配置程序”(实现WebMvcConfigurationSupport
)的支持。这些类具有非常相似的方法,但其工作原理大致如下:
支持组件会找到所有配置程序,并将它们组合到最终配置中。
我最近用quite a long post撰写了code examples的内容,我建议尝试使用小型Spring Boot应用程序并对其进行调试-令人大开眼界。
Boot的默认实现为WebMvcConfigurer
,它做了很多工作-包括查找实现WebMvcConfigurationSupport
的bean并使用它们。如果您接管并实施支持类,Boot将找到它,禁用默认支持类,您将完全处于控制之下。但是随后,许多默认的自动魔术消失了,如果需要,您必须使用它。