springboot踩坑篇-01--@EnableWebMvc注解和@EnableAutoConfiguration 注解

springboot踩坑篇-01

springboot踩坑篇-01–@EnableWebMvc注解和@EnableAutoConfiguration 注解
问题出现

最近项目在用springboot开发,项目当中要用到spring的拦截器;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jcl.gycms.entity.LoginLogs;
import com.jcl.gycms.service.LoginLogsService;

/**

  • @author zpf

  • @version 1.0
    */
    @Component
    public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private LoginLogsService loginLogsService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception {
    return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
    ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    throws Exception {
    String username = (String) request.getSession().getAttribute(“isLogin”);
    if(StringUtils.isNotBlank(username)) {
    LoginLogs loginLogs = new LoginLogs();
    loginLogs.setLoginname(username);
    loginLogs.setLogintime(new Date());
    String localAddr = request.getLocalAddr();
    String ip = request.getRemoteAddr();
    System.out.println("–localAddr"+localAddr+"----ip"+ip);
    loginLogs.setLoginip(request.getLocalAddr());
    int i = loginLogsService.saveSelective(loginLogs);
    if(i>0) {
    System.out.println(“记录登录日志-----成功”);
    }
    }
    }
    }

在配置拦截器时用到了@EnableWebMvc
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**

  • @author zpf

  • @version 1.0
    */
    @EnableWebMvc
    @Configuration
    public class LoginConfiguration extends WebMvcConfigurerAdapter{

    @Bean
    LoginInterceptor localInterceptor() {
    System.out.println(“将拦截器注册成bean”);
    return new LoginInterceptor();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    System.out.println(“拦截登录了-------------------”);
    // 注册拦截器
    LoginInterceptor loginInterceptor = new LoginInterceptor();
    InterceptorRegistration loginRegistry = registry.addInterceptor(loginInterceptor);
    // 拦截路径
    loginRegistry.excludePathPatterns("/WEB-INF/jsp");
    loginRegistry.addPathPatterns("/adminLogin/**");

    }
    }

然后项目可以正常启动,但是当我访问项目是
在这里插入图片描述

查看后台发现报错Could not resolve view with name ‘index’ in servlet with name ‘dispatcherServlet’–路径映射不到,但是也没想到问题所在,于是只能问万能的度娘了
在这里插入图片描述
问题解决
参考了https://blog.youkuaiyun.com/testcs_dn/article/details/80249894微wx笑的博客发现是@EnableWebMvc这个注解的问题
在这里插入图片描述
使用 @EnableWebMvc 注解,需要以编程的方式指定视图文件相关配置;
使用 @EnableAutoConfiguration 注解,会读取 application.properties 或 application.yml 文件中的配置。

解决1
换成@EnableAutoConfiguration
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**

  • @author zpf

  • @version 1.0
    */
    @EnableAutoConfiguration
    @Configuration
    public class LoginConfiguration extends WebMvcConfigurerAdapter{

    @Bean
    LoginInterceptor localInterceptor() {
    System.out.println(“将拦截器注册成bean”);
    return new LoginInterceptor();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    System.out.println(“拦截登录了-------------------”);
    // 注册拦截器
    LoginInterceptor loginInterceptor = new LoginInterceptor();
    InterceptorRegistration loginRegistry = registry.addInterceptor(loginInterceptor);
    // 拦截路径
    loginRegistry.excludePathPatterns("/WEB-INF/jsp");
    loginRegistry.addPathPatterns("/adminLogin/**");

    }
    }

然后得到解决,可以访问了
在这里插入图片描述

解决二
在入口类注入视图解析器

import javax.servlet.MultipartConfigElement;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@MapperScan({“com.jcl.gycms.mapper”})
public class GycmsApplication {
public static void main(String[] args) {
SpringApplication.run(GycmsApplication.class, args);
}
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//单个文件最大
factory.setMaxFileSize(“10240KB”); //KB,MB
//设置总上传数据总大小
factory.setMaxRequestSize(“102400KB”);
return factory.createMultipartConfig();
}

@Bean
public InternalResourceViewResolver setupViewResolver() {
	InternalResourceViewResolver resolver = new InternalResourceViewResolver();
	/** 设置视图路径的前缀 */
	resolver.setPrefix("/WEB-INF/jsp/");
	/** 设置视图路径的后缀 */
	resolver.setSuffix(".jsp");
	return resolver;
}

}

<think>好的,我现在需要帮助用户了解在Spring Boot中如何正确使用@EnableWebMvc注解,包括它的正确位置、使用场景注意事项。首先,我应该回忆一下Spring BootSpring MVC的基本知识,以及@EnableWebMvc的作用。 我记得,Spring Boot的自动配置机制会自动配置Spring MVC,当检测到相关的类在类路径下时。自动配置会提供默认的视图解析器、静态资源处理等。而@EnableWebMvc是一个来自Spring框架的注解,用于启用MVC配置,类似于通过XML配置中的<mvc:annotation-driven>。这个注解会导入Spring MVC的配置,覆盖Spring Boot的默认自动配置。 用户的问题是,这个注解应该添加在哪种配置类中,使用场景注意事项是什么。根据之前的引用,特别是引用[1]中的@SpringBootApplication注解,它组合了@SpringBootConfiguration、@EnableAutoConfiguration@ComponentScan。默认情况下,Spring Boot的自动配置已经处理了MVC的相关配置,所以通常不需要添加@EnableWebMvc,否则会禁用自动配置的默认行为。 接下来需要确认使用场景。比如,当用户需要完全自定义MVC配置,而不是使用Spring Boot的默认设置时,才需要使用@EnableWebMvc。例如,自定义拦截器、格式化程序、视图控制器等,这时候需要在一个配置类上添加@EnableWebMvc,并可能继承WebMvcConfigurerAdapter或实现WebMvcConfigurer接口来覆盖默认方法。 注意事项方面,添加@EnableWebMvc会导致自动配置失效,因此像静态资源路径(如classpath:/static/)的处理可能需要自己配置。另外,配置类应该放在可以被组件扫描到的位置,通常主应用类在同一包或子包下。引用[2]中提到@ComponentScan的作用,所以如果配置类不在扫描路径下,可能导致配置不生效。 需要验证是否正确。比如,在Spring Boot应用中,如果添加了@EnableWebMvc,则自动配置的MVC部分会被禁用,用户必须手动配置所有需要的部分。例如,静态资源可能无法访问,除非在配置类中明确添加资源处理器。同时,引用[4]中提到的多环境配置可能与此无关,但引用[3]中的配置导入可能与自定义配置相关,但这里主要涉及的是Java配置而非属性文件。 总结一下,正确的做法是将@EnableWebMvc添加到带有@Configuration注解的配置类中,并且仅在需要完全控制MVC配置时使用。同时要注意这会覆盖默认配置,需要手动处理相关设置。可能还需要参考官方文档或可靠资料来确认这些信息,确保回答的准确性。</think>在Spring Boot中使用`@EnableWebMvc`注解需要谨慎,以下是详细解答: --- ### **一、@EnableWebMvc的正确使用位置** `@EnableWebMvc`应添加到**自定义配置类**中,且该类需满足以下条件: 1. 使用`@Configuration`注解标记,表明这是一个配置类; 2. 通常与主启动类(`@SpringBootApplication`)同级或位于其子包中,确保被组件扫描到[^2]; 3. 示例: ```java @Configuration @EnableWebMvc public class WebMvcConfig implements WebMvcConfigurer { // 自定义MVC配置 } ``` --- ### **二、使用场景** 1. **完全自定义MVC配置** 当需要覆盖Spring Boot的默认MVC自动配置时(例如自定义拦截器、视图解析器、消息转换器等)[^1]。 2. **手动控制WebMvcConfigurer** 需实现`WebMvcConfigurer`接口并重写方法(如`addInterceptors`、`addViewControllers`)时。 3. **禁用自动配置** 添加`@EnableWebMvc`会禁用Spring Boot的`WebMvcAutoConfiguration`,此时需手动实现所有MVC相关配置[^1]。 --- ### **三、注意事项** 1. **谨慎使用** Spring Boot已通过`WebMvcAutoConfiguration`提供了合理的默认配置(如静态资源路径`classpath:/static/`、JSON序列化等)。除非需要完全自定义,否则不建议添加`@EnableWebMvc`[^4]。 2. **静态资源失效问题** 启用`@EnableWebMvc`后,默认的静态资源路径(如`/static/**`)将失效,需手动配置: ```java @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/"); } ``` 3. **与自动配置的冲突** 避免同时使用`@EnableWebMvc``@SpringBootApplication`中的自动配置逻辑,否则可能导致配置冲突。 --- ### **四、典型错误场景** - **错误示例**:在主启动类上直接添加`@EnableWebMvc`,导致自动配置被禁用且未提供替代方案: ```java @SpringBootApplication @EnableWebMvc // 错误!导致默认配置失效 public class Application { ... } ``` --- ### **五、替代方案** 若只需部分自定义MVC行为(如添加拦截器),**无需启用`@EnableWebMvc`**,直接通过实现`WebMvcConfigurer`接口即可: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new CustomInterceptor()); } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值