使用 Spring 引导,Autowire 在电报应用程序中不起作用
Autowire not work in telegram app using Spring Boot
我使用 java 库 TelegramBots 制作了我的电报机器人,还在我的应用程序中使用了 SpringBoot。
当在 class TelegramBotPolling 中调用方法 onUpdateReceived 而不是字段 busStationBtnsGenerator 为空。
如何正确自动装配字段 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
{
.....
}
}
使用构造函数 new 创建的 class 实例不受 Spring 管理。在这种情况下,为了引用它,您应该使用 this 关键字。
@PostConstruct
public void registerBot(){
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
telegramBotsApi.registerBot(this);
} catch (TelegramApiException e) {
logger.error(e);
}
我使用 java 库 TelegramBots 制作了我的电报机器人,还在我的应用程序中使用了 SpringBoot。
当在 class TelegramBotPolling 中调用方法 onUpdateReceived 而不是字段 busStationBtnsGenerator 为空。
如何正确自动装配字段 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
{
.....
}
}
使用构造函数 new 创建的 class 实例不受 Spring 管理。在这种情况下,为了引用它,您应该使用 this 关键字。
@PostConstruct
public void registerBot(){
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
telegramBotsApi.registerBot(this);
} catch (TelegramApiException e) {
logger.error(e);
}