Search code examples
javaspringspring-boot

How to call a service from Main application calls Spring Boot?


I'm building a Spring Boot application that will be called from command line. I will pass to application some parameters but I'm having problems to call a service from this class:

@SpringBootApplication
public class App{

    public static void main(String[] args) {

        SpringApplication.run(App.class, args);

        App app = new App();
        app.myMethod();    
    }

    @Autowired
    private MyService myService;

    private void myMethod(){
        myService.save();
    }
}

I'm trying to call a method from inside the main but I'm getting the error:

Exception in thread "main" java.lang.NullPointerException
at com.ef.Parser.App.myMethod(Application.java:26)
at com.ef.Parser.App.main(Application.java:18)

Solution

  • you can create a class that implements CommandLineRunner and this will be invoked after the app will start

    @Component
    public class CommandLineAppStartupRunner implements CommandLineRunner {
        @Autowired
        private MyService myService;
    
        @Override
        public void run(String...args) throws Exception {
           myService.save();
    
        }
    }
    

    you can get farther information on this here