@Resource 注入为null

@Resource

@Resource可以用于注入对象
一般我们在编码中都会使用@Resource来注入一个实例对象,但是特殊情况下可能会是null。
这个时候可以用SpringUtil.getBean()来手动获取

代码示例

private HbaseProperties hbaseProperties = SpringUtil.getBean(HbaseProperties.class);

补充:为何会注入的是null

  1. 没有被spring管理,比如没有加@Component
  2. 如果对象是手动new出来的,那么对象里的成员变量依赖的类用@Resource注解注入就会是null。因为不受spring管理
@Component
public class A {
    
    @Resource
    B a;
    
    public B getBStance(){
        return b;
    }
}

@Component
public class B {
    
    private Integer i;
}

public class Test {
    
    @Resource
    A a;

    public void test() {
        A a1 = new A();
        a1.getBStance();// 此为空
    
        a.getBStance();// B实例
    }
    
}

posted on 2022-04-26 17:04  Iversonstear  阅读(6139)  评论(0编辑  收藏  举报

导航