@Autowired注入问题

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项目入口类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值