spring boot 拦截器中无法注入 serivce,autowired 失败

这里需要用到两个注解: @Lazy 和 @Autowired

1、@Lazy

注解是spring框架里的,只有一个属性默认值为 true;即加上注解,就开启了懒加载。

import org.springframework.context.annotation.Lazy;

@Lazy

2、@Autowired

同为spring框架中的注解,自动注入 spring 容器管理的 Bean 

import org.springframework.beans.factory.annotation.Autowired;

解释:

@Autowired(required=true):

@Autowired 默认 required 属性值为 true,即注入时,该bean必须已经初始化在spring容器中,否则注入失败,程序报错。


@Autowired(required=false):

表示当前要注入的 bean 可以不存在,如果有直接注入,没有则跳过;

实际没什么用,如果在拦截器中直接使用,也会报错

 

解决:

@Lazy 和 @Autowired 结合使用,这样就可以注入进去了

@Lazy
@Autowired
SysParamService sysParamService;

 

 

你可能感兴趣的:(Java,SpringBoot)