@EnableWebMvc介绍和使用详细demo

@EnableWebMvc是什么

@EnableWebMvcSpring MVC 中的一个注解,它用于启用 Spring MVC 框架的基本功能,以便你可以使用 Spring MVC 提供的特性来处理 Web 请求。
通常情况下,在基于 Spring Boot 的应用中,并不需要显式地使用 @EnableWebMvc,因为 Spring Boot 已经默认自动配置了 Spring MVC。但是,如果你想要自定义 Spring MVC 的配置,或者禁用 Spring Boot 对 Spring MVC 的自动配置,那么你就需要显式地使用 @EnableWebMvc。

使用示例

下面是一个简单的使用 @EnableWebMvc 的示例:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    // 配置静态资源处理
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
    // 配置视图解析器
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/views/", ".jsp");
    }
    // 其他自定义的 Spring MVC 配置
}

在上面的示例中,@EnableWebMvc 注解被添加到了一个 @Configuration 注解的类上,表示要启用 Spring MVC 框架。在这个类中,你可以添加自定义的 Spring MVC 配置,例如添加拦截器、视图解析器、消息转换器等。

需要注意的是,使用 @EnableWebMvc 会完全覆盖 Spring Boot 对 Spring MVC 的自动配置,因此如果你使用了 @EnableWebMvc,就需要自己配置 Spring MVC 的全部内容,包括视图解析器、资源处理、异常处理等。通常情况下,只有在需要非常精细的控制 Spring MVC 配置时才会使用 @EnableWebMvc。

总结:

使用@EnableWebMvc注解,可以开启Spring MVC 框架的基本功能,你可以使用 Spring MVC 提供的特性来处理 Web 请求,同时会完全覆盖 Spring Boot 对 Spring MVC 的自动默认配置。

@EnableWebMvc介绍和使用详细demo_第1张图片

你可能感兴趣的:(springmvc,springboot,开发技巧,mvc,springboot)