spring boot @Autowired spring bean报null错误

1、有问题的写法 :这种写法会导致 proMapper为null 。控制台报空指针异常

@Component
public class Test {
	@Autowired
    private ProMapper proMapper;
    
    public void a(){
        DataGridResidentDO s = proMapper.getDataGridResident("72398e73-e122-4cd3-a381-2d8342960170", "才存村网格");
        System.out.println();
    }
}

2、正确的写法

@Component
public class Test {
    private static ProMapper proMapper;
    @Autowired
    public void setRepository(ProMapper repository) {
        Test.proMapper = repository;
    }

    public void a(){
        DataGridResidentDO s = proMapper.getDataGridResident("72398e73-e122-4cd3-a381-2d8342960170", "才存村网格");
        System.out.println();
    }
}

注:以上为博主的测试类,命名、书写不规范。需按照实际进行修改

总结:在tomcat启动的线程中如何使用spring容器提供的@Autowired的单例bean呢?
如果不是static,这个repository就是null
在线程中也没有办法从spring容器中取到这个bean,所以只能把这个bean设置为static,这样单例bean就脱离了spring容器的限制

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值