Spring-Boot - Access to JpaRepository outside the Controller scope

Viewed 642

I have a Web application on SpringBoot, but it also handles a specific protocol and this is started with ServerSocket that waits for connections and handles it properly. Below is an example of how I'm doing this:

  public class MyServer extends Thread {
    @Autowired
    private MyRepository myRepo;

    public MyServer() {
      start();
    }

    public run() {
     ServerSocket server = new ServerSockey(7000);
     while (true) {
       Socket sock = server.accept();
       ...
       // Handle connection here
       myRepo.findById(1);
       ...
      }
  }
}

My Repository is:

@Repository
public interface MyRepository extends JpaRepository<MyModel, Long> {
}

And my main method, that starts it:

@SpringBootApplication(exclude= {SecurityAutoConfiguration.class})
@ComponentScan(basePackages={"myComponentPackages"})
@EnableJpaRepositories(basePackages= {"myRepositoriesPackages"})
public class Main {

    public static void main(String[] args) {        
            new MyServer();

            SpringApplication springApp = new SpringApplication(Main.class);
            springApp.setBannerMode(Banner.Mode.OFF);
            springApp.run(args);
        }
}

Of course I have a lot more, eg controllers, repositories, etc., but it serves as an example of what I need. In this case, I need to access the MyRepository instance on MyServer, but as it is not within the scope of a Controller, which is called when a request is made to the web server, the @Autowired annotation does not work and the myRepo variable is always as null. The question is: How to access this repository outside the context of a rest call?

Any tips?

Tks in advance, Leandro

0 Answers
Related