我在同一个 Spring Boot 中有 2 个 CommandLineRunner

mma*_*ran 3 spring-boot

我在 Spring Boot 中有 2 个实现命令行运行程序的类。它们基本上是这样的:

 @SpringBootApplication
 @ComponentScan("com.xxxx")
 public class Application implements CommandLineRunner {
Run Code Online (Sandbox Code Playgroud)

第二个看起来像:

 @SpringBootApplication
 @ComponentScan("com.xxxx")
 public class ApplicationWorklfow implements CommandLineRunner {
Run Code Online (Sandbox Code Playgroud)

他们编译得很好。但是当我尝试使用 java -jar 运行它时,我可能会收到一个错误,因为 spring 不知道要运行哪个。

是否有我可以使用的命令来告诉 jar 我正在尝试运行哪个应用程序?

K. *_*ddy 5

您可以拥有任意数量的CommandLineRunnerbean,但应该只有一个可以具有@SpringBootApplication注释的入口点类。尝试删除 上的@SpringBootApplication注释ApplicationWorklfow

PS:

似乎您的主要要求是有条件地启用 2 个 CommandLineRunner bean 之一。您只能拥有一个 Application 类并使用@Profile@ConditionalOnProperty等条件启用 CLR bean 。

拥有多个带@SpringBootApplication注释的入口点类并不是一个好主意。

@SpringBootApplication
public class Application {

}

@Component
@Profile("profile1")
public class AppInitializer1 implements CommandLineRunner {

}

@Component
@Profile("profile2")
public class AppInitializer2 implements CommandLineRunner {

}
Run Code Online (Sandbox Code Playgroud)

现在您可以按如下方式激活您想要的配置文件:

java -jar -Dspring.profiles.active=profile1 app.jar
Run Code Online (Sandbox Code Playgroud)

随着概貌被激活,只有AppInitializer1运行。

PS: PS:

如果由于某种原因您仍然想配置 mainClass 您可以执行以下操作:

   <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>          
      <configuration>
        <mainClass>${start-class}</mainClass>
      </configuration>

    </plugin>
Run Code Online (Sandbox Code Playgroud)

您可以利用 Maven 配置文件为不同的配置文件提供不同的类。有关更多信息,请参阅https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/maven-plugin/usage.html