Exception Processing ErrorPage[errorCode=0, location=/error],拦截器注入@Autowired为空

本文介绍了在Spring框架中配置拦截器时遇到的空指针异常问题及其解决方案。错误配置导致拦截器在Spring上下文加载前执行,通过@Bean注解提前注册拦截器到Spring上下文中可以解决此问题。

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

参考文章:https://blog.youkuaiyun.com/wenxingchen/article/details/78708845

在拦截器中使用@Autowired时,报空指针.发现拦截器的加载时间在Spring上下文之前加载,所以需要提前将拦截器注册到Spring上下文中

错误配置:

@Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 可添加多个
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**");

    }

正确配置

@Bean
    public HandlerInterceptor getMyInterceptor(){
        return new LoginInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(getMyInterceptor());

    }
@Slf4j @RequestMapping("/emps") @RestController public class EmpController { @Autowired private EmpService empService; /** * 分页查询 */ @GetMapping public Result page(EmpQueryParam empQueryParam){ log.info("分页查询: {}", empQueryParam); PageResult<Emp> pageResult = empService.page(empQueryParam); return Result.success(pageResult); } /** * 新增员工 */ @PostMapping public Result save(@RequestBody Emp emp) throws Exception { log.info("新增员工: {}", emp); empService.save(emp); return Result.success(); } /** * 删除员工 - 数组 */ /* @DeleteMapping public Result delete(Integer[] ids){ log.info("删除员工: {}", Arrays.toString(ids)); return Result.success(); }*/ /** * 删除员工 - List */ @DeleteMapping public Result delete(@RequestParam List<Integer> ids){ log.info("删除员工: {}", ids); empService.delete(ids); return Result.success(); } /** * 根据ID查询员工信息 */ @GetMapping("/{id}") public Result getInfo(@PathVariable Integer id){ log.info("根据ID查询员工信息: {}", id); Emp emp = empService.getInfo(id); return Result.success(emp); } /** * 修改员工 */ @PutMapping public Result update(@RequestBody Emp emp){ log.info("修改员工: {}", emp); empService.update(emp); return Result.success(); } /** * 查询所有的员工 */ @GetMapping("/list") public Result list(){ log.info("查询所有的员工数据"); List<Emp> empList = empService.list(); return Result.success(empList); } } public class PageResult<T> { private Long total; private List<T> rows; } @Data public class Result { private Integer code; //编码:1成功,0为失败 private String msg; //错误信息 private Object data; //数据 public static Result success() { Result result = new Result(); result.code = 1; result.msg = "success"; return result; } public static Result success(Object object) { Result result = new Result(); result.data = object; result.code = 1; result.msg = "success"; return result; } public static Result error(String msg) { Result result = new Result(); result.msg = msg; result.code = 0; return result; } } 根据我后端的接口和返回的数据类型在整理一份
最新发布
07-20
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值