【SpringBoot】中的ApplicationRunner接口 和 CommandLineRunner接口
warning:
这篇文章距离上次修改已过414天,其中的内容可能已经有所变动。
在SpringBoot中,ApplicationRunner和CommandLineRunner接口可以用来在SpringBoot应用启动完成后执行一些特定的操作。这两个接口都只包含一个方法,run方法,它们的区别在于CommandLineRunner接口的run方法参数是命令行参数,而ApplicationRunner接口的run方法参数是一个ApplicationArguments对象,它提供对命令行参数的更丰富的控制和操作。
以下是使用ApplicationRunner和CommandLineRunner的简单示例:
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner: 参数列表是:" + String.join(", ", args));
}
}
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner: 参数列表是:" + args.getSourceArgs());
}
}在这个例子中,MyCommandLineRunner类实现了CommandLineRunner接口,并重写了run方法,该方法接收命令行参数作为字符串数组。MyApplicationRunner类实现了ApplicationRunner接口,并重写了run方法,该方法接收ApplicationArguments对象,它提供了更多的命令行参数的上下文信息。
当SpringBoot应用启动时,这两个实现了上述接口的组件会自动被Spring框架实例化并执行它们的run方法。
评论已关闭