springboot 学习之路 9 (项目启动后就执行特定方法) - 阳602 - 博客园
Spring Boot学习--项目启动时执行特定方法_最是那一低头的温柔的博客-优快云博客
针对上面的问题,我在spring boot中找到了解决方案。那就是spring boot给我们提供了两个接口 ApplicationRunner和CommandLineRunner。这两个接口是Springboot给我们提供了两种“开机启动”的方式
ApplicationRunner :
源码如下:
public interface ApplicationRunner {
void run(ApplicationArguments var1) throws Exception; }
CommandLineRunner :
源码如下:
public interface CommandLineRunner {
void run(String... var1) throws Exception; } 对比: 相同点:这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法。我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication 执行之后开始执行的。 不同点:CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用ApplicationArguments 用来接收参数的 【根据业务场景灵活运用】
针对上面的问题,我在spring boot中找到了解决方案。那就是spring boot给我们提供了两个接口 ApplicationRunner和CommandLineRunner。这两个接口是Springboot给我们提供了两种“开机启动”的方式
ApplicationRunner :
源码如下:
public interface ApplicationRunner {
void run(ApplicationArguments var1) throws Exception;
}
CommandLineRunner :
源码如下:
public interface CommandLineRunner {
void run(String... var1) throws Exception;
}
对比:
相同点:这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法。我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication 执行之后开始执行的。
不同点:CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用ApplicationArguments 用来接收参数的 【根据业务场景灵活运用】
/**
* @Author:huhy
* @DATE:Created on 2018/1/3 12:47
* @Modified By:
* @Class 项目启动后运行此方法:CommandLineRunner实现
*/
@Component
@Order(value=2)
public class FtpInitRunner implements CommandLineRunner {
@Override
/**
*@Author: huhy
*@Package_name:com.huhy.web.common.runner
*@Date:13:20 2018/1/3
*@Description:项目启动后运行此方法 CommandLineRunner
* //项目路径 path = E:\IDE\workspace\ideaWorkspace\spring boot\spring-boot
String path = System.getProperty("user.dir");
CommandLine.main(new String[]{path+"\\src\\main\\resources\\ftpserver\\ftpd-typical.xml"});
System.out.println("----------------------"+path);
*/
public void run(String... var1) throws Exception{
System.out.println("2222222222222222222222");
}
/**
* @Author:huhy
* @DATE:Created on 2018/1/3 13:20
* @Modified By:
* @Class Description:ApplicationRunner 实现
*/
@Component
@Order(value = 1) //执行顺序控制
public class FtpInitRunner2 implements ApplicationRunner{
@Override
/**
*@Author: huhy
*@Package_name:com.huhy.web.common.runner
*@Date:13:29 2018/1/3
*@Description: ApplicationRunner方式实现
*/
public void run(ApplicationArguments applicationArguments) throws Exception {
//项目路径 path = E:\IDE\workspace\ideaWorkspace\spring boot\spring-boot
String path = System.getProperty("user.dir");
CommandLine.main(new String[]{path+"\\src\\main\\resources\\ftpserver\\ftpd-typical.xml"});
System.out.println("----------------------"+path);
System.out.println("111111111111111111111111");
}
spring boot的项目启动注意分为两步:
实现相应接口(ApplicationRunner和CommandLineRunner) -----------》 加入注解 (@Component | @Order )