Spring-Boot - Accessing Jparepository outside the Controller scope

Asked

Viewed 60 times

1

Hello, I have a web application based on Springboot, but that also treats a specific protocol and for this I start a Serversocket that waits for connections and treats them appropriately. 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);
       ...
      }
  }
}

The Repositorio is declared below:

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

And my main class, which starts it all:

@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, for example controllers, Positorios, etc., but it serves as an example of what I need. In this case, I need to access the Myrepository instance on Myserver,but since 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 null. The question is: How to access this repository outside the context of a Rest call, e.g.?

Any hint ?

Thank you, Leandro

  • Utilize @Configurable in your class MyServer

  • Thanks. but it didn’t work. It’s still null the reference to my repository. I’ve tried with @Service tbem, but it won’t. It seems to me that it only works when a call occurs to my Rest via Controller services. But there must be a way to get access to the dependency injection engine, because it is running after all.

1 answer

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.