当前位置 博文首页 > 逐墨飞扬的博客:SpringBoot应用启动成功后回调

    逐墨飞扬的博客:SpringBoot应用启动成功后回调

    作者:[db:作者] 时间:2021-07-12 15:45

    应用

    如果你有一些资源需要在SpringBoot启动后预加载, 可以通过SpringBoot给我们提供了两个接口完成: CammandLineRunnerApplicationRunner。两个接口的工作方式类似,如果有多个启动回调接口实现类,我们还可以通过添加@Order注解指定顺序

    使用示例:

    @Component
    @Order(1)
    public class Runner implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println("The Runner start to initialize ...");
        }
    }
    

    示例

    CommandLineRunner接口
    /**
     * 该类可用于SpringBoot应用启动后提前做一些初始化操作,比如缓存数据
     */
    @Slf4j
    @Component
    public class MyInitialization implements CommandLineRunner {
    
    	// args 可以获取启动应用时通过命令行传进来的参数
    	@Override
    	public void run(String... args) throws Exception {
    		log.info("应用启动了,我准备初始化数据了");
    		for(String arg : args) {
    			log.info("arg: " + arg);
    		}
    	}
    }
    
    ApplicationRunner接口
    /**
     * 该类可用于SpringBoot应用启动后提前做一些初始化操作,比如缓存数据
     */
    @Slf4j
    @Component
    public class MyInitialization2 implements ApplicationRunner {
    
    	// ApplicationArguments 参数获取形如:--name=zhangsan --gender=nan 格式的命令行参数
    	@Override
    	public void run(ApplicationArguments args) throws Exception {
    		log.info("应用启动了,我准备初始化数据了");
    		for(String argKey : args.getOptionNames()) {
    			log.info("参数key: " + argKey+",参数值:" + args.getOptionValues(argKey));
    		}
    	}
    }
    
    cs
    下一篇:没有了