我可以为Spring Boot应用创建多个入口点吗?
在Spring Boot中 ,需要指定一个主类,它是应用程序的入口点。 通常,这是一个带有标准主方法的简单类,如下所示;
@SpringBootApplication public class MySpringApplication { public static void main(String [] args) { SpringApplication.run(MySpringApplication.class, args); } }
然后,在运行应用程序时,将此类指定为主入口点。
但是,我想使用config来运行我的代码,使用config来定义它,而不使用不同的jar
! (我知道重建jar会让我指定一个替代的主类,但这实际上给了我两个应用程序,而不是一个!所以,我怎么能这样做来利用一个带有两个主类的jar
并选择一个通过Spring application.yml文件?
我会坚持只有一个主类和主方法的原始模式,但是在该方法中你可以配置你想去的地方。 也就是说,而不是有两个主要方法和配置哪个被调用使这两个方法只是常规方法,并创建一个主要方法,使用配置来确定您的两个方法中的哪一个运行。
我找到了答案 – 使用CommandLineRunner接口……
所以现在我有两节课;
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 }
以及如何在配置中切换它们
@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文件中,使用
app.runner=1