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

In SpringBoot 2.x you can simply run the application by SpringApplication.run method and operate on the returned ApplicationContext. Complete example below:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import java.util.Arrays;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
        SomeService service = applicationContext.getBean(SomeService.class);
        service.doSth(args);
    }
}

@Service
class SomeService {

    public void doSth(String[] args){
        System.out.println(Arrays.toString(args));
    }
}

Leave a Comment