Python 官方文档:入门教程 => 点击学习
目录概述实现启动加载接口ApplicationRunner接口的示例CommandLineRunner接口示例CommandLineRunner和ApplicationRunner的
开发中可能会有这样的场景,需要在容器启动的时候执行一些内容。比如读取配置文件,数据库连接之类的。
SpringBoot给我们提供了两个接口来帮助我们实现这种需求。
两个启动加载接口分别是:
CommandLineRunner
ApplicationRunner
他们的执行时机是容器启动完成的时候。
这两个接口中有一个run方法,我们只需要实现这个方法即可。这个两个接口的不同之处在于:
ApplicationRunner中的run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。
package com.jDDDemo.demo.controller;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
@Order(value = 1)
public class JDDRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println(args);
System.out.println("这个是测试ApplicationRunner接口");
}
}
执行结果如下:
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("<这个是测试CommandLineRunn接口");
}
}
在Spring Boot程序中,我们可以使用不止一个实现CommandLineRunner和ApplicationRunner的bean。
为了有序执行这些bean的run()方法,可以使用@Order注解或Ordered接口。
下面例子中创建了两个实现CommandLineRunner接口bean和两个实现ApplicationRunner接口的bean。
CommandLineRunnerBean1.java
@Component
@Order(1)
public class CommandLineRunnerBean1 implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("CommandLineRunnerBean 1");
}
}
ApplicationRunnerBean1.java
@Component
@Order(2)
public class ApplicationRunnerBean1 implements ApplicationRunner {
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("ApplicationRunnerBean 1");
}
}
CommandLineRunnerBean2.java
@Component
@Order(3)
public class CommandLineRunnerBean2 implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("CommandLineRunnerBean 2");
}
}
ApplicationRunnerBean2.java
@Component
@Order(4)
public class ApplicationRunnerBean2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("ApplicationRunnerBean 2");
}
}
输出结果为:
CommandLineRunnerBean 1
ApplicationRunnerBean 1
CommandLineRunnerBean 2
ApplicationRunnerBean 2
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: SpringBoot中的ApplicationRunner与CommandLineRunner问题
本文链接: https://www.lsjlt.com/news/168777.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0