zoukankan      html  css  js  c++  java
  • springboot项目启动之后初始化自定义配置类

    前言

    今天在写项目的时候,需要再springboot项目启动之后,加载我自定义的配置类的一些方法,百度了之后特此记录下。

    正文

    方法有两种:

    1、 创建自定义类实现 CommandLineRunner接口,重写run()方法。springboot启动之后会默认去扫描所有实现了CommandLineRunner的类,并运行其run()方法。

    @Component
    @Order(2)   //通过order值的大小来决定启动的顺序
    public class AskForLeave implements CommandLineRunner {
    
        @Override
        public void run(String... args) throws Exception {
            askForLeave();
        }
    
        public void askForLeave(){
            System.out.println("项目启动了,执行了方法");
        }
    }

    运行结果:

     2、创建自定义类实现ApplicationRunner 接口,重写run()方法。

    @Component
    @Order(3)
    public class Hello implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) throws Exception {
    
            hello();
        }
    
        public void hello(){
            System.out.println("项目又启动了,这次使用的是:继承 ApplicationRunner");
        }
    }

    结果如下:

    关于二者的区别:

    其实并没有什么区别,如果想获取更加详细的参数的时候,可以选择使用ApplicationRunner接口。其参数类型为:ApplicationArguments 。

  • 相关阅读:
    nginx入门与实战
    python开发之virtualenv与virtualenvwrapper讲解
    Linux下的python3,virtualenv,Mysql、nginx、redis安装配置
    Linux系统基础优化及常用命令
    vim与程序员
    Shell基本命令
    Linux之文档与目录结构
    远程连接Linux
    oracle 根据时间戳查询date类型sql
    oracle 锁用户
  • 原文地址:https://www.cnblogs.com/chenmc/p/9253230.html
Copyright © 2011-2022 走看看