java 方式配置spring mvc 继承WebMvcConfigurerAdapter和继承WebMvcConfigurationSupport

本文探讨了使用Java配置Spring MVC的方法,对比分析了WebMvcConfigurerAdapter与WebMvcConfigurationSupport两个类的功能差异,阐述了它们在配置视图解析器及静态资源处理上的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 java 的方式配置 sping mvc 时遇到一个疑问,在spring in action 这本书中 配置 mvc 时 采用 继承 WebMvcConfigurerAdapter 类

@Configuration
@EnableWebMvc
@ComponentScan(
        basePackages = Constants.MVC_PACKAGE_PATH,
        useDefaultFilters = false,
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class})}
)
public class MvcConfig extends WebMvcConfigurerAdapter {

    private static final String VIEW_PREFIX = "/";// 视图前缀
    private static final String VIEW_SUFFIX = ".jsp";// 视图后缀
    private static final String VIEW_CONTENT_TYPE = "text/html;charset=UTF-8";//视图的内容类型。

    /**
     * 配置 视图解析器
     * @return
     */
    @Bean
    public ViewResolver viewResolver(){

        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setCache(true);
        resolver.setPrefix(VIEW_PREFIX);
        resolver.setSuffix(VIEW_SUFFIX);
        resolver.setExposeContextBeansAsAttributes(true);
        resolver.setContentType(VIEW_CONTENT_TYPE);
        return resolver;
    }

    /**
     * 配置静态资源处理
     * @param configurer
     */
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

查阅网上其他资料时发现,其他大神也有采用继承自WebMvcConfigurationSupport 这个类。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = Constants.BASE_PACKAGE_PATH, useDefaultFilters = false, includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class})
})
public class MvcConfig extends WebMvcConfigurationSupport {
...
}

顿时对这两个类产生疑问,对比发现

  1. 两个类都是来自包org.springframework.web.servlet.config.annotation
  2. 两个类都可以实现配置mvc。两者都可以配置视图解析器以及静态资源等
    总结:
    WebMvcConfigurationSupport 与WebMvcConfigurerAdapter 都可以配置MVC,WebMvcConfigurationSupport 支持的自定义的配置更多更全,WebMvcConfigurerAdapter有的WebMvcConfigurationSupport 都有
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT从业者的职业生涯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值