Spring Boot 使用Sping Boot 时,自动布线在电报应用程序中不起作用

neskvpey  于 5个月前  发布在  Spring
关注(0)|答案(1)|浏览(66)

我使用Java库TelegramBots制作电报机器人,并在应用程序中使用SpringBoot。
当在类TelegramBotPolling中调用方法onUpdateReceived时,字段busStationBtnsGenerator为null。
如何正确自动连接字段busStationBtnsGenerator,以便在调用onUpdateReceived方法时不为null?
这是我的代码的一个简单例子:

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

}

字符串

idv4meu8

idv4meu81#

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

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

字符串

相关问题