我可以为 Spring Boot 应用程序创建多个入口点吗?

jon*_*y.l 3 java config spring-boot

Spring Boot中,需要指定一个主类,它是应用程序的入口点。通常,这是一个具有标准 main 方法的简单类,如下所示;

@SpringBootApplication
public class MySpringApplication {

    public static void main(String [] args) {
        SpringApplication.run(MySpringApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,当应用程序运行时,该类被指定为主入口点。

但是,我想使用不同的主类运行我的代码,使用配置来定义它,并且不使用不同的jar!(我知道重建 jar 将使我能够指定一个替代主类,但这实际上给了我两个应用程序,而不是一个!那么,我如何才能利用一个jar具有两个主类的应用程序,并通过 Spring 选择要使用的一个应用程序 application.yml文件?

jon*_*y.l 6

我找到了答案 - 使用 CommandLineRunner 界面...

所以现在我有两节课;

public class ApplicationStartupRunner1 implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
    //implement behaviour 1 
}
Run Code Online (Sandbox Code Playgroud)

public class ApplicationStartupRunner2 implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
    //implement behaviour 2
}
Run Code Online (Sandbox Code Playgroud)

以及如何在配置中在它们之间切换..

@Configuration
public class AppConfig {

    @Value("${app.runner}")
    private int runner;

    @Bean
    CommandLineRunner getCommandLineRunner() {
        CommandLineRunner clRunner = null;
        if (runner == 1) {
            clRunner = new ApplicationStartupRunner1();
        } (else if runner == 2) {
            clRunner = new ApplicationStartupRunner2();
        } else {
            //handle this case..
        }

        return clRunner;
    }
}
Run Code Online (Sandbox Code Playgroud)

最后在 application.properties 文件中,使用

app.runner=1
Run Code Online (Sandbox Code Playgroud)