【问题标题】:Autowire not work in telegram app using Spring BootAutowire 在使用 Spring Boot 的电报应用程序中不起作用
【发布时间】:2017-09-15 13:52:31
【问题描述】:

我使用 java 库 TelegramBots 制作我的电报机器人,并在我的应用程序中使用 SpringBoot。

当在类 TelegramBotPolling 中调用方法 onUpdateReceived 时,字段 busStationBtnsGenerator 为空。

如何正确地自动装配字段 busStationBtnsGenerator 以便在调用 onUpdateReceived 方法时它不会为空?

这是我的代码的简短示例:

@Component
public class TelegramBotPolling extends TelegramLongPollingBot {

    @Autowired
    BusStationBtnsGenerator busStationBtnsGenerator;

    static {
        ApiContextInitializer.init();
    }

    @PostConstruct
    public void registerBot(){

         TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
         try {
           telegramBotsApi.registerBot(new TelegramBotPolling());
         } catch (TelegramApiException e) {
           logger.error(e);
    }
    }


    @Override
    public void onUpdateReceived(Update update) {   
      // When this method is called field "busStationBtnsGenerator" is  null. 
    }   
}



@Component
public class BusStationBtnsGeneratorImpl implements BusStationBtnsGenerator {

   @Autowired
   BusStationsParser stationsParser;

   @Autowired
   UrlHelper urlHelper;


   @Override
   public InlineKeyboardMarkup getKeyboardMarkupForBusStations() 
   throws Exception 
   {
       ......
   }

  private List<List<InlineKeyboardButton>> getBusStationButtons() 
  throws Exception 
  {
      .....
  }

}

【问题讨论】:

  • 请粘贴 BusStationBtnsGenerator 类
  • TelegramBotPolling 类是 spring bean 吗?
  • @Kick,我在我的问题中添加了 **BusStationBtnsGenerator ** 类。
  • @pvpkiran,没有 TelegramBotPolling 不是 spring bean 类。它是我用来连接到我的电报机器人的第三方库。
  • TelegramBotPolling 类上没有任何注释,在上面添加组件

标签: java spring-boot telegram-bot long-polling


【解决方案1】:

使用构造函数 new 创建的类的实例不由 Spring 管理。在这种情况下,您应该使用 this 关键字来引用它。

@PostConstruct
public void registerBot(){
     TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
     try {
       telegramBotsApi.registerBot(this);
     } catch (TelegramApiException e) {
       logger.error(e);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-22
    相关资源
    最近更新 更多