共通の特徴を持っているいくつかのデータの初期化操作を行うには、プロジェクトの段階でスタート、ときにのみ、プロジェクトの開始、もはや実行していない後:システムタスク
リスナーのServletContextListenerで定義された3つのコンポーネント(サーブレット、フィルター、リスナー)のウェブベース、そしてあなたは、プロジェクトの立ち上げや破壊に耳を傾け、その後、適切なデータ操作を初期化し、破壊することができます。
public class MyListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
//在这里做数据初始化操作
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
//在这里做数据备份操作
}
}
春ブーツは2つのソリューションですCommandLineRunnerとApplicationRunnerを提供しています
SpringBoot CommandLineRunner
CommandLineRunnerを使用する場合は、カスタムMyCommandLineRunner CommandLineRunnerインタフェースを実現します:
@Component // @Compoent 注解将 MyCommandLineRunner 注册为Spring容器中的一个 Bean。
@Order(100) //@Order注解,表示这个启动任务的执行优先级,在一个项目中,启动任务可能有多个,所以需要有一个排序。@Order 注解中,数字越小,优先级越大,默认情况下,优先级的值为 Integer.MAX_VALUE,表示优先级最低。
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception { n 方法的参数,来自于项目的启动参数,即项目入口类中,main方法的参数会被传到这里。
//启动任务的核心逻辑,当项目启动时,run方法会被自动执行。
}
}
SpringBoot ApplicationRunner
ApplicationRunner一貫したCommandLineRunner機能、使用が唯一の違いは、主にプロセスのパラメータに反映され、基本的に同じであり、ApplicationRunnerパラメータを受信することができるApplicationRunner CommandLineRunner以外のパラメータ(より多くの種類を受信することができ、またの形でキー/値を受信することができます。パラメータ)。
実装インタフェースApplicationRunner、登録コンポーネントとコンポーネントの優先順位とCommandLineRunner同じ構成は次のようにすることを利用ApplicationRunner、カスタムクラス:
@Component
@Order(98)
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
List<String> nonOptionArgs = args.getNonOptionArgs(); //可以用来获取命令行中的无key参数(和CommandLineRunner一样)。
System.out.println("MyApplicationRunner>>>"+nonOptionArgs);
Set<String> optionNames = args.getOptionNames(); //可以用来获取所有key/value形式的参数的key。
for (String key : optionNames) {
System.out.println("MyApplicationRunner>>>"+key + ":" + args.getOptionValues(key)); //可以根据key获取key/value 形式的参数的value。
}
String[] sourceArgs = args.getSourceArgs(); //则表示获取命令行中的所有参数。
System.out.println("MyApplicationRunner>>>"+Arrays.toString(sourceArgs));
}
}
java -jar devtools-0.0.1-SNAPSHOT.jar 三国演义 西游记 --age=99