好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring Boot命令行运行器的实现方法

commandlinerunner是一个带有run方法的简单spring引导接口。spring boot启动后将自动调用实现commandlinerunner接口的所有bean的run方法。

command line runner在加载应用程序上下文之后以及spring application run方法完成之前执行,相当于你的应用的初始化过程,一般用来实现一些数据预先加载或预先处理。

?

1

2

3

4

5

6

7

8

9

10

11

@springbootapplication

<b> public </b> <b> class </b> demoapplication implements commandlinerunner {

   <b> private </b> <b> final </b> logger logger = loggerfactory.getlogger(demoapplication.<b> class </b>);

   <b> public </b> <b> static </b> <b> void </b> main(string args) {

     springapplication.run(demoapplication.<b> class </b>, args);

   }

   @override

   <b> public </b> <b> void </b> run(string... strings) throws exception {

    ....

   }

}

上面的run方法参数是 命令行 参数,使用java -jar 启动这个应用的命令行参数。

如果有多个命令行运行器,可以进行排序:

?

1

2

3

4

5

6

7

@component

@order ( 1 )

<b> public </b> <b> class </b> anotherdatabaseloader implements commandlinerunner {

 

@component

@order ( 2 )

<b> public </b> <b> class </b> dataloader implements commandlinerunner {

另外一种在主应用的写法:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

@springbootapplication

<b> public </b> <b> class </b> unsplashapplication {

   <b> public </b> <b> static </b> <b> void </b> main(string args) {

     springapplication.run(unsplashapplication.<b> class </b>, args);

   }

   @bean

   commandlinerunner runner(){

     <b> return </b> args -> {

       system.out.println(<font> "commandlinerunner running in the unsplashapplication class..." </font><font>);

     };

   }

}

</font>

总结

以上所述是小编给大家介绍的spring boot命令行运行器的实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

原文链接:https://HdhCmsTestjdon测试数据/50511

查看更多关于Spring Boot命令行运行器的实现方法的详细内容...

  阅读:16次