spring 自动注入运行时空指针异常

背景:

   系统接入telegram ,通过new telegram() 方式进行使用,发现telegram中的autowired的bean 为null。

解决方法:

   如果一个类中有spring容器注入(autowired)的对象,则不能使用new来创建对象,必须使用 @Autowired或者 @Resource来创建该对象。这样就可以把对象交给spring容器进行管理。

public class BotConfiguration {
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BonusInformBot bonusInformBot;

    @Bean
    public boolean registerBot(){
        if(!redisUtil.hasKey("test-rot")){
            try {
                TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
                botsApi.registerBot(bonusInformBot);// 这里之前new BonusInformBot(),现在改为autowired,类 BonusInformBot中autowired的对象就正常使用
            } catch (TelegramApiException e) {
                log.info("机器人初始化失败:{}",e.getMessage());
                e.printStackTrace();
            }
            redisUtil.set("test-rot","test-rot",300);
        }
        return true;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值