无法调用,因为“this.Repository”为空

问题描述 投票:0回答:1
@SpringBootApplication
public class TelegramBotApplication {
    public static void main(String[] args) throws IOException, TelegramApiException {
        SpringApplication.run(TelegramBotApplication.class, args);
        TelegramBotsApi botsApi = new TelegramBotsApi(DefaultBotSession.class);
        botsApi.registerBot(new TelegramBot());
    }
}
@Component
public class TelegramBot extends TelegramLongPollingBot {

    @Autowired
    private NewsRepository newsRepository;

    @Value("${bot.name}")
    private String botName;

    @Value("${bot.token}")
    private String botToken;

    @Override
    public String getBotUsername() {

        return "EconomicNowBot";
    }

    @Override
    public String getBotToken() {
        return "7153170793:AAEzPuNdBrDUIMi-EAOe27McWHXAqiT8gok";
    }

    @Override
    public void onUpdateReceived(Update update) {
        var originalMessage = update.getMessage();
        System.out.println(originalMessage.getText());

       var response =  new SendMessage();
       response.setChatId(originalMessage.getChatId().toString());
       response.setText(newsRepository.findByLink("https://ria.ru/20240413/vektor-1939795251.html").getTitle());
       sendAnswerMessage(response);
    }

    private void sendAnswerMessage(SendMessage message) {
        if(message != null){
            try {
                execute(message);
            }catch (Exception e){

            }
        }
    }
}
@Repository
public interface NewsRepository extends JpaRepository<News,Long> {
    News findByLink(String link);
}

java.lang.NullPointerException: Cannot invoke "com.telegramBot.NewsRepository.findByLink(String)" because "this.newsRepository" is null at com.telegramBot.bot.TelegramBot.onUpdateReceived(TelegramBot.java:41) ~[classes/:na] at java.base/java.util.ArrayList.forEach(ArrayList.java:1596) ~[na:na] at org.telegram.telegrambots.meta.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27) ~[telegrambots-meta-6.3.0.jar:na] at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:317) ~[telegrambots-6.3.0.jar:na]

当我尝试使用 onUpdateRecieve 方法 response.setText(newsRepository.findByLink("https://ria.ru/20240413/vektor-1939795251.html").getTitle()); 时出现空指针异常我得到它是因为我的存储库为空,尽管我自动连接了我的存储库

java spring spring-boot dependency-injection repository
1个回答
0
投票

将其添加到您的 TelegramBot 类中。

公共 TelegramBot(NewsRepository newsRepository){

}

© www.soinside.com 2019 - 2024. All rights reserved.