背景:
系统接入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;
}
}