0
点赞
收藏
分享

微信扫一扫

SpringBoot 官方文档示例:(9)在SpringApplication.run方法完成之前读取命令行参数添加额外的处理逻辑


可通过实现ApplicationRunner和CommandLineRunner来实现
1、CommandLineRunner

package cn.edu.tju.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
if(args!=null&&args.length>0){
for(String str: args){
//可以在这里添加更多的处理逻辑,本例只是简单打印
System.out.println(str);
}
}
}
}

2.ApplicationRunner

package cn.edu.tju.runner;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
String[] sourceArgs = args.getSourceArgs();
//可以在这里添加更多的处理逻辑,本例只是简单打印
for(int i=0;i<sourceArgs.length;i++){
System.out.println(sourceArgs[i]);
}
}
}

打包,执行

java -jar D:\springboot266\target\springboot266-1.0-SNAPSHOT.jar --username=newton

可以在程序启动时看到输出:

SpringBoot 官方文档示例:(9)在SpringApplication.run方法完成之前读取命令行参数添加额外的处理逻辑_ide


上述bean还可以通过@Order注解来控制执行顺序


举报

相关推荐

0 条评论