Ability to configure CLI as non-repl

@SpringBootApplication
public class NonInteractiveCliApp {

    /**
     * Configures non-interactive shell mode.
     */
    @Configuration
    public static class NonInteractiveConfig {

        @Autowired
        private ConfigurableEnvironment environment;

        @PostConstruct
        public void disableInteractiveShell() {
            InteractiveShellApplicationRunner.disable(environment);
        }

        @Bean
        @Lazy
        public NonInteractiveShellApplicationRunner nonInteractiveShellApplicationRunner(Parser parser, Shell shell) {
            return new NonInteractiveShellApplicationRunner(parser, shell);
        }

    }

    @Order(NonInteractiveShellApplicationRunner.PRECEDENCE)
    @RequiredArgsConstructor
    public static class NonInteractiveShellApplicationRunner implements ApplicationRunner {

        public static final int PRECEDENCE = InteractiveShellApplicationRunner.PRECEDENCE - 100;

        private final Parser parser;
        private final Shell shell;

        @Override
        public void run(ApplicationArguments args) throws Exception {
            String rawArgs = Arrays.stream(args.getSourceArgs()).collect(Collectors.joining(" "));
            Reader reader = new StringReader(rawArgs);

            // Use FileInputProvider to read the input arguments (it has little to do with files in fact).
            InputProvider inputProvider = new FileInputProvider(reader, parser);
            shell.run(inputProvider);
        }
    }

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(NonInteractiveCliApp.class)
                .web(WebApplicationType.NONE)
                .run(args);
    }
}

原文链接: https://github.com/spring-projects/spring-shell/issues/241

posted @ 2021-04-28 10:47  豆腐居士  阅读(43)  评论(0编辑  收藏  举报