How to test JpaRepository using main class instead of test class or controller in Spring Boot application

Viewed 49

Say i have a repository:

public interface UserRepository extends JpaRepository<User, Long>{
    List<User> findAll();
}

If i want to test out what the result will be (using System.out.println) I know only one way:

Make a Controller class like so:

@RestController
@RequestMapping("/hey")
class Controller{

@Autowired
UserRepository repository;

@GetMapping()
public void hey(){
System.out.println(repository.findAll());
}
}

And then i have to start up the SpringBootApplication:

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}


surf to localhost:8080/hey

And only then i see on the console what the result is.

This is so cumbersome and time-consuming, especially when the spring boot app is heavy and takes a long time to load.

What i would have loved to do is to comment out the springbootapplication and just make a temporary class that i run from the main class and print the results that way. That is so much faster.

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        //SpringApplication.run(App.class, args);
          new Temp().go();
    }
}

Class Temp{

@Autowired
UserRepository repository;

public void go(){
System.out.println(repository.findAll());
}
}

This isn't possible as its an interface and it asks you to implement every single method it has. How can i just print the results on the console of a repository without having to use controller ?

1 Answers

As you mentionned if you comment SpringApplication.run Spring DI won't work because the Spring context is not yet configured with required beans.

What you can do to achieve your goal, first you need to keep SpringApplication.run and you can inject the repository as follows in your main class:

@SpringBootApplication
public class App{

    public static UserRepository repository;

    @Autowired
    public App(UserRepository repository) {
        App.repository= repository;
    }

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);

        System.out.println(repository.findAll());
    }
}
Related