我可以创建一个Spring Boot应用程序的多个入口点吗? [英] Can I create multiple entry points to a Spring Boot app?

查看:300
本文介绍了我可以创建一个Spring Boot应用程序的多个入口点吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Spring Boot, a main class needs to be specified, which is the entry point to the app. Typically this is a simple class with a standard main method, as follows;

@SpringBootApplication
public class MySpringApplication {

    public static void main(String [] args) {
        SpringApplication.run(MySpringApplication.class, args);
    }
}

然后在以下情况下将此类指定为主要入口点:该应用程序运行。

This class is then specified as the main entry point when the application runs.

但是,我想使用不同的主类(使用config来定义)来运行我的代码,而无需使用其他 jar ! (我知道重建jar将使我能够指定一个替代的主类,但这实际上给了我两个应用程序,而不是一个!!因此,我该如何利用一个 jar 有两个主要类,然后通过Spring application.yml 文件选择一个?

However, I want to run my code using a different main class using config to define this, And without using a different jar!! (I know rebuilding the jar will enable me to specify an alternative main class, but this effectively gives me two apps, not one! So, how can I do this to utilise one jar with two main classes and select the one to use via the Spring application.yml file?

推荐答案

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

I found an answer - use the CommandLineRunner interface...

所以现在我有两个类;

So now I have two classes;

public class ApplicationStartupRunner1 implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
    //implement behaviour 1 
}

public class ApplicationStartupRunner2 implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
    //implement behaviour 2
}

以及如何在配置中进行切换。

and how to switch between them in config..

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

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

and finally in the application.properties file, use

app.runner=1

这篇关于我可以创建一个Spring Boot应用程序的多个入口点吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆