Autowire 在使用 Spring Boot 的电报应用程序中不起作用

问题描述 投票:0回答:2

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

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

如何正确自动装配字段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 
  {
      .....
  }

}
java spring-boot telegram-bot long-polling
2个回答
2
投票

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

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

0
投票

你能修好它吗?我也遇到过这样的事

© www.soinside.com 2019 - 2024. All rights reserved.