Home > Software design >  How to wire Spring Bean and Telegram Bot common java class?
How to wire Spring Bean and Telegram Bot common java class?

Time:05-19

I have a standard TelegramBot realization like:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
     ...
     TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
     telegramBotsApi.registerBot(new Bot());
     ...

And Bot class:

public class Bot extends TelegramLongPollingBot {

    @Override
    public void onUpdateReceived(Update update) {
        Message inMessage = getMessage(update);
        fireMessage(inMessage.getChatId(), "TEST");
    }
 ....

And I have JPA Repository like

@Repository
public interface BondsRepo extends JpaRepository<Bond, Long>{
    List<Bond> findAllByUser(ArNoteUser user);
}

that I use in my controller without any problem:

@RestController
@RequestMapping("/investing")
public class InvestController {
    private final BondsRepo bondsRepo;  
    public InvestController(BondsRepo bondsRepo) {
        this.bondsRepo = bondsRepo;
    }
...

But when I use that repo in Bot class I naturally get NPE, because Bot.class is a common Java class, but BondsRepo is Spring Bean and it does not accessible outside Spring Context.

What is right way to access data by using JPA Repo in my Bot class?

CodePudding user response:

I think you should inject the Repository into the Bot.class via the constructor.

In order to do that you could retrieve a bean from SpringContext in your main:

...
ConfigurableApplicationContext appContext = SpringApplication.run(Application.class, args);
BondsRepo repo = appContext.getBean(BondsRepo.class);
Bot bot = new Bot(repo);
...
telegramBotsApi.registerBot(bot);
...
  • Related