【问题标题】:Multiple Spring boot CommandLineRunner based on command line argument基于命令行参数的多个 Spring boot CommandLineRunner
【发布时间】:2017-11-12 20:40:52
【问题描述】:

我已经使用 spring 云任务创建了 spring boot 应用程序,它应该执行一些命令(任务)。 每个任务/命令都是短期任务,所有任务都是从命令行开始,做一些简短的 ETL 工作并完成执行。

有一个包含所有命令/任务的 spring boot jar。 每个任务都是 CommandLineRunner,我喜欢根据命令行的参数来决定将执行哪些任务(一个或多个)。 这样做的最佳做法是什么? 我不喜欢脏代码问“if else”之类的问题。

【问题讨论】:

  • 如果 jar 文件中有多个主类,则可以在命令行中发出 java -classpath myapp.jar com.example.Task1 而不是 java -jar myapp.jar。看不到 if-else。为什么讨厌 if-else 呢?程序有时需要分支。
  • 谢谢,我不确定 Spring Boot 是否允许使用多个主类。使用硬编码的 if-else 更难维护然后注入组件

标签: java spring-boot spring-cloud-task


【解决方案1】:

Spring Boot 运行应用程序上下文中的所有 CommandLineRunner 或 ApplicationRunner bean。您不能通过任何参数选择一个。

所以基本上你有两种可能性:

  1. 您有不同的CommandLineRunner 实现,并在每个实现中检查参数以确定这个特殊的CommandLineRunner 是否应该运行。
  2. 您只实现了一个CommandLineRunner,它充当调度程序。代码可能如下所示:

这是您的跑步者将实现的新界面:

public interface MyCommandLineRunner {
    void run(String... strings) throws Exception;
}

然后您定义实现并用名称标识它们:

@Component("one")
public class MyCommandLineRunnerOne implements MyCommandLineRunner {
    private static final Logger log = LoggerFactory.getLogger(MyCommandLineRunnerOne.class);

    @Override
    public void run(String... strings) throws Exception {
        log.info("running");
    }
}

和

@Component("two")
public class MyCommandLineRunnerTwo implements MyCommandLineRunner {
    private static final Logger log = LoggerFactory.getLogger(MyCommandLineRunnerTwo.class);
    @Override
    public void run(String... strings) throws Exception {
        log.info("running");
    }
}

然后在您的单个 CommandLineRunner 实现中,您获取应用程序上下文并按名称解析所需的 bean,我的示例仅使用第一个参数,并将其称为 MyCommandLineRunner.run()method:

@Component
public class CommandLineRunnerImpl implements CommandLineRunner, ApplicationContextAware {
    private ApplicationContext applicationContext;


    @Override
    public void run(String... strings) throws Exception {
        if (strings.length < 1) {
            throw new IllegalArgumentException("no args given");
        }

        String name = strings[0];
        final MyCommandLineRunner myCommandLineRunner = applicationContext.getBean(name, MyCommandLineRunner.class);
        myCommandLineRunner.run(strings);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

【讨论】:

  • 我们正在尝试使用 spring cli 的命令 CliCommand 注释来实现它。似乎每个命令都像“main”一样已经从命令行解析参数
  • 所以这与 Spring Boot CommandLine Runner 不同;抱歉,没用过
  • 这两种方法都不太合理......只是去 3 层高的 switch 语句,......我不想这么说,但它保持得更好。依赖注入,肯定是 100%,一旦你超越了,虽然......
【解决方案2】:

您还可以使您的 CommandLineRunner 实现 @Component 和 @ConditionalOnExpression("${someproperty:false}")

然后有多个配置文件,将 someproperty 设置为 true 以将这些 CommandLineRunners 包含在上下文中。

@Component
@Slf4j
@ConditionalOnExpression("${myRunnerEnabled:false}")
public class MyRunner implements CommandLineRunner {
    @Override
    public void run(String ... args) throws Exception {
        log.info("this ran");
    }
}

在 yml application-myrunner.yml 中

myRunnerEnabled: true
@SpringBootApplication
public class SpringMain {
    public static void main(String ... args) {
        SpringApplication.run(SpringMain.class, args);
    }
}

【讨论】:

  • 当一个应用程序以及另一个依赖工件都实现了 CommandLineRunner 时,这是一个优雅的解决方案。如果没有这个解决方案,两个实现类都会被执行。
【解决方案3】:

奇怪的是没有内置机制来选择一组 CommandLineRunner。默认情况下,它们都被执行。

我已经重用了 - 也许不正确 - Profile 机制,也就是说,我用 @org.springframework.context.annotation.Profile("mycommand") 注释了每个 CommandLineRunner,然后我选择了我想用系统执行的那个属性 -Dspring.profiles.active=mycommand

关于Profile机制的更多信息,请参考https://www.baeldung.com/spring-profiles

【讨论】:

    【解决方案4】:

    类似于这个答案https://stackoverflow.com/a/44482525/986160,但使用注入和更少的配置。

    有类似的要求,对我有用的是让一个 CommandLineApps 类实现 CommandLineRunner,然后将我所有其他命令行运行器注入为 @Component 并使用第一个参数委托给注入的一个跑步者。请注意,注入的不能扩展CommandLineRunner,也不能注释为@SpringBootAppplication。

    重要提示:请注意,如果您将调用放在 crontab 中,如果未完成调用,前一个调用会破坏。

    这是一个例子:

    @SpringBootApplication
    public class CommandLineApps implements CommandLineRunner {
    
        @Autowired
        private FetchSmsStatusCmd fetchSmsStatusCmd;
    
        @Autowired
        private OffersFolderSyncCmd offersFolderSyncCmd;
    
        public static void main(String[] args) {
            ConfigurableApplicationContext ctx = SpringApplication.run(CommandLineApps.class,  args);
            ctx.close();
        }
    
        @Override
        public void run(String... args) {
    
            if (args.length == 0) {
                return;
            }
    
            List<String> restOfArgs = Arrays.asList(args).subList(1, args.length);
    
            switch (args[0]) {
                case "fetch-sms-status":
                    fetchSmsStatusCmd.run(restOfArgs.toArray(new String[restOfArgs.size()]));
                    break;
                case "offers-folder-sync":
                    offersFolderSyncCmd.run(restOfArgs.toArray(new String[restOfArgs.size()]));
                    break;
            }
        }
    }
    
    @Component
    public class FetchSmsStatusCmd {
    
        [...] @Autowired dependencies    
    
        public void run(String[] args) {
    
            if (args.length != 1) {
                logger.error("Wrong number of arguments");
                return;
            }
            [...]
        }
     }
    

    【讨论】:

      猜你喜欢
      • 2020-08-06
      • 2015-01-19
      • 1970-01-01
      • 2017-05-26
      • 2017-02-02
      • 2020-01-17
      • 2020-04-28
      • 2018-09-28
      • 2020-12-17
      相关资源
      最近更新 更多