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

neskvpey  于 2024-01-06  发布在  Spring
关注(0)|答案(1)|浏览(140)

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

  1. @Component
  2. public class TelegramBotPolling extends TelegramLongPollingBot {
  3. @Autowired
  4. BusStationBtnsGenerator busStationBtnsGenerator;
  5. static {
  6. ApiContextInitializer.init();
  7. }
  8. @PostConstruct
  9. public void registerBot(){
  10. TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
  11. try {
  12. telegramBotsApi.registerBot(new TelegramBotPolling());
  13. } catch (TelegramApiException e) {
  14. logger.error(e);
  15. }
  16. }
  17. @Override
  18. public void onUpdateReceived(Update update) {
  19. // When this method is called field "busStationBtnsGenerator" is null.
  20. }
  21. }
  22. @Component
  23. public class BusStationBtnsGeneratorImpl implements BusStationBtnsGenerator {
  24. @Autowired
  25. BusStationsParser stationsParser;
  26. @Autowired
  27. UrlHelper urlHelper;
  28. @Override
  29. public InlineKeyboardMarkup getKeyboardMarkupForBusStations()
  30. throws Exception
  31. {
  32. ......
  33. }
  34. private List<List<InlineKeyboardButton>> getBusStationButtons()
  35. throws Exception
  36. {
  37. .....
  38. }
  39. }

字符串

idv4meu8

idv4meu81#

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

  1. @PostConstruct
  2. public void registerBot(){
  3. TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
  4. try {
  5. telegramBotsApi.registerBot(this);
  6. } catch (TelegramApiException e) {
  7. logger.error(e);
  8. }

字符串

相关问题