【问题标题】:I have 2 CommandLineRunner in same Spring boot我在同一个 Spring Boot 中有 2 个 CommandLineRunner
【发布时间】:2018-10-02 06:59:55
【问题描述】:

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

 @SpringBootApplication
 @ComponentScan("com.xxxx")
 public class Application implements CommandLineRunner {

第二个看起来像:

 @SpringBootApplication
 @ComponentScan("com.xxxx")
 public class ApplicationWorklfow implements CommandLineRunner {

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

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

【问题讨论】:

    标签: spring-boot


    【解决方案1】:

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

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

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

    java -jar -Dspring.profiles.active=profile1 app.jar
    

    激活 profile1 后,只有 AppInitializer1 会运行。

    PS:PS:

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

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

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

    【讨论】:

    • 那我怎么告诉java我想运行ApllicationWoklfow。在那次启动?
    • 在我的回答中添加了更多信息。
    猜你喜欢
    • 2017-02-02
    • 2019-03-21
    • 2017-05-26
    • 2015-02-23
    • 1970-01-01
    • 2017-11-12
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多