1. @Autowired注入static接口问题
@Autowired自动注入,如:
@Component
public class IDGeneratorUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void UserId(){
}
}
如果注入static修饰的RedisTemplate则注入不了,如:
@Component
public class IDGeneratorUtil {
@Autowired
private static RedisTemplate<String, Object> redisTemplate;
public static void userId(){
}
}
处理以上问题:
@Component
public class IDGeneratorUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
private static IDGeneratorUtil generatorUtil;
@PostConstruct
public void init() {
generatorUtil = this;
generatorUtil.redisTemplate = this.redisTemplate;
}
public static void userId(){
this.redisTemplate.opsForValue().set(USER_KEY, userNumber);
}
}
解释:
@Autowired:作用于构建器、属性、方法。按byType自动注入。(@Resource默认按 byName自动注入)
@PostConstruct:被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。(PreDestroy()方法在destroy()方法执行执行之后执行)
2. 导致@Autowired注入失败的问题
在一次测试当中,发现 @Autowired 无法注入的问题,使用redisTemplate时,发现为null!
原因:RedisTemplate被static所修饰,Spring依赖注入是依赖set方法,而set方法是普通的对象方法,static变量是类的属性,所以无法完成注入操作。
@Autowired按类型进行自动注入,如果匹配不到对应的类型,也会出现注入失败。
一般来说就是没有被ioc容器进行管理,在容器中匹配不到类型,需要注解(@Service,@repository,@Component等)纳入spring IOC容器中
还有一种情况,当所有注解正常,可能是因为SpringBoot项目的Bean装配默认规则是根据Application类所在的包位置从上往下扫描!“Application类”是指SpringBoot项目入口类。