Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a simple main with Spring Boot

I use last Spring Boot, I just neet to run a method and stop program execution after the last instruction, just like à main.

Juste need to run this method :

public class Main {

    @Autowired
    private MyService myService;

    public void run() throws IOException {
        System.out.println(myService.listAll());
    }
}

And the Application class is a simple Spring Boot run

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) throws IOException {
        SpringApplication.run(Application.class, args);
    }
}

So, how to tell to spring boot to run Main.run() with command like java -jar myapp.jar ?

Thank you

like image 214
Maryo Avatar asked Sep 13 '25 19:09

Maryo


1 Answers

Make your Main implement CommandLineRunner and annotate it with @Component so that it's found by component scanning:

@Component
public class Main implements CommandLineRunner {

    private final MyService myService;

    @Autowired
    Main(MyService myService) {
        this.myService = myService;
    }

    @Override
    public void run(String... args) throws IOException {
        System.out.println(this.myService.listAll());
    }
}
like image 155
Andy Wilkinson Avatar answered Sep 16 '25 09:09

Andy Wilkinson