Search code examples
javaspring-boottelegram-botlong-polling

Autowire not work in telegram app using Spring Boot


I make my telegram bot using java library TelegramBots and also use SpringBoot in my application.

When in class TelegramBotPolling there is called method onUpdateReceived than the field busStationBtnsGenerator is null.

How corectly autowire field busStationBtnsGenerator in order it will be not null when onUpdateReceived method is called ?

This is brief example of my code:

@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 
  {
      .....
  }

}

Solution

  • Instance of class created with constructor new is not managed by Spring. For referring it you should you this keyword in this case.

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