前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >1.7分钟学会Spring Boot的CommandLineRunner

1.7分钟学会Spring Boot的CommandLineRunner

作者头像
ImportSource
发布2018-04-03 15:26:17
1.5K0
发布2018-04-03 15:26:17
举报
文章被收录于专栏:ImportSource

本文介绍一个非常酷的Spring Boot接口,名字叫做CommandLineRunner。

使用这个接口,你可以在Spring的Bean们以及Application Context被创建之后,来做一些事情。也就是在程序启动的时候做一些事情。

来自Spring Boot 文档

If you want access to the raw command line arguments, or you need to run some specific code once the SpringApplication has started you can implement the CommandLineRunner interface. The run(String… args) method will be called on all Spring beans implementing this interface. You can additionally implement the @Ordered interface if several CommandLineRunner beans are defined that must be called in a specific order.

如果要访问raw命令行参数,或者在SpringApplication启动后需要运行一些特定代码,可以实现 CommandLineRunner接口。 run(String ... args)方法将在实现此接口的所有Spring bean上调用。 如果你定义了多个 CommandLineRunner bean必须按特定顺序调用的话,那么你可以再实现一个接口@Ordered就可以了。

下面是一个来自NixMash Spring简单的例子:

代码语言:javascript
复制
@Component
public class ApplicationLoader implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationLoader.class);

    @Override
    public void run(String... strings) throws Exception {
        StringBuilder sb = new StringBuilder();
        for (String option : strings) {
            sb.append(" ").append(option);
        }
        sb = sb.length() == 0 ? sb.append("No Options Specified") : sb;
        logger.info(String.format("WAR launched with following options: %s", sb.toString()));
    }
}

这是一个有点多余的小函数,只是记录一下在命令行启动WAR文件时使用的命令行参数。

有趣的是,上面的 ApplicationLoader类是在NixMash Spring JPA RootContext模块中,但是MVC WebContext模块中的 @SpringBootApplication将拾取该类,因为我们添加了 @Component注释并实现了 CommandLineRunner接口。

下面是从命令行启动的一个示例:

$ java -jar nixmashSpring.war --spring.one=one --spring.two=two

启动后,就可以看到输出了我们runner里边打印的内容,在第三行:

当然在实际的开发中,你通常想要使用 CommandLineRunner做比我们在这里做的更多的事。比如,你可以使用该接口注入Spring Cloud Zuul的filter。 你也可以使用 CommandLineRunner的另外一个实现 JobLauncherCommandLineRunner,通过这个接口你可以在Spring Batch中运行批处理作业。

总之,你要记住CommandLineRunner!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-01-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 ImportSource 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档