栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot拦截器注入service为null【踩坑记录】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot拦截器注入service为null【踩坑记录】

以下这种方式能注册拦截器,也能使用,但是获取到注入的service 是null。

我的拦截器类

@Component
public class LesionInterceptor implements HandlerInterceptor {

	@Autowired
	private IOrganizationService organizationService;
	
	// TODO 其他代码
}

配置类

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

	@Bean
	public MyWebMvcConfig getMyWebMvcConfig() {
		MyWebMvcConfig myWebMvcConfig = new MyWebMvcConfig() {
			@Override
			public void addViewControllers(ViewControllerRegistry registry) {
				// registry.addViewController("/").setViewName("alogin");
				// registry.addViewController("/login").setViewName("alogin");
				// registry.addViewController("/main.html").setViewName("dashboard");
			}

			// 注册拦截器
			@Override
			public void addInterceptors(InterceptorRegistry registry) {
				registry.addInterceptor(new LesionInterceptor())
						.addPathPatterns("
@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {

	//这里的LesionInterceptor 是上面定义的拦截器的类型
	@Bean
	public LesionInterceptor MyWebMvcConfig() {
//		MyWebMvcConfig myWebMvcConfig = new MyWebMvcConfig() {
//			@Override
//			public void addViewControllers(ViewControllerRegistry registry) {
//				// registry.addViewController("/").setViewName("alogin");
//				// registry.addViewController("/login").setViewName("alogin");
//				// registry.addViewController("/main.html").setViewName("dashboard");
//			}
//
//			// 注册拦截器
//			@Override
//			public void addInterceptors(InterceptorRegistry registry) {
//				registry.addInterceptor(new LesionInterceptor())
//						.addPathPatterns("/**")
//						.excludePathPatterns("/login", "/swagger", "/",
//								"/swagger-resources/**", "/webjars/**",
//								"/v2/**", "/swagger-ui.html/**");
//				super.addInterceptors(registry);
//			}
//		};
		return new LesionInterceptor();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		//多个拦截器组成一个拦截器链
		// addPathPatterns用于添加拦截规则
		// excludePathPatterns用户排除拦截
		//对来自/** 全路径请求进行拦截
		registry.addInterceptor(MyWebMvcConfig()).addPathPatterns("/**");

	}

}


至此解决,
还有一种方式就是继承 WebMvcConfigurerAdapter,但是这种方式已经过时。可参考 https://blog.csdn.net/wmh13262227870/article/details/77005920

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/880696.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号