简体   繁体   English

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

[英]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. 我使用Java库TelegramBots制作了电报机器人,并在我的应用程序中使用了SpringBoot。

When in class TelegramBotPolling there is called method onUpdateReceived than the field busStationBtnsGenerator is null. 当在TelegramBotPolling类中调用onUpdateReceived方法时, busStationBtnsGenerator字段为null。

How corectly autowire field busStationBtnsGenerator in order it will be not null when onUpdateReceived method is called ? 调用onUpdateReceived方法时,如何自动连线现场busStationBtnsGenerator以便其不为null?

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

}

Instance of class created with constructor new is not managed by Spring. Spring不会管理使用构造函数new创建的类的实例。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM