Spring Boot 自定义拦截器(HandlerInterceptor)使用@Autowired注入接口为null解决方法

本文介绍了在Spring Boot自定义HandlerInterceptor时,使用@Autowired注解注入CacheService出现null的问题。原因是拦截器加载早于SpringApplicationContext创建。解决办法是通过提前加载MyInterceptor来确保依赖注入正常。
摘要由CSDN通过智能技术生成

自定义拦截器代码中使用@Autowired注入CacheService为null

配置信息代码

package com.ding.config;

import com.ding.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfigurer implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }
}

无注入时没有问题,但有注入运行拦截器中CacheService的结果为null。

造成注入CacheService为null的原因

是因为拦截器加载是在SpringApplicationContext创建之前完成的,所以在拦截器中注入实体CacheService就为null。

解决方法

在MyInterceptor提前加载,配置信息修改如下:

packa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值