Can I create multiple entry points to a Spring Boo

2019-05-23 10:51发布

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.

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?

2条回答
我命由我不由天
2楼-- · 2019-05-23 11:19

I would stick with the original pattern of having just one main class and main method, however within that method you could configure where you want to go. I.e. rather than having 2 main methods and configuring which gets called make these 2 methods just normal methods, and create one main method which uses the config to determine which of your two methods get run.

查看更多
forever°为你锁心
3楼-- · 2019-05-23 11:22

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 
}

and

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

and finally in the application.properties file, use

app.runner=1
查看更多
登录 后发表回答