如何从主应用程序调用Spring Boot的服务?

2022-09-01 09:17:17

我正在构建一个将从命令行调用的Spring Boot应用程序。我将向应用程序传递一些参数,但是从此类调用服务时遇到问题:

@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();
    }
}

我试图从main内部调用一个方法,但我得到错误:

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)

答案 1

您可以创建一个实现CommandLineRunner的类,这将在应用程序启动后被调用

@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
    @Autowired
    private MyService myService;

    @Override
    public void run(String...args) throws Exception {
       myService.save();

    }
}

您可以在此处获取有关此内容的更多信息


答案 2

在SpringBoot 2.x中,您可以简单地通过方法运行应用程序,并对返回的AppplicationContext进行操作。完整的示例如下:SpringApplication.run

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));
    }
}

推荐