SpringBoot起動時にメソッドを自動的に実行させるいくつかの実装方式(転載)

1763 ワード

テキストリンク:https://mp.weixin.qq.com/s/1KJ4BscJWM5cunLClGwlHA
1.サーブレットContextAwareインタフェースを実現し、そのsetサーブレットContextメソッドを書き換える
@Component
public class TestStarted implements ServletContextAware {
    /**
     *  bean 
     *  initializingbean afterpropertiesset init 
     *
     */
    @Override
    public void setServletContext(ServletContext servletContext) {
        System.out.println("setServletContext ");
    }
}

注:このメソッドは、通常のBeanのプロパティを入力しますが、Beanの初期化はまだ行われていません.
2.サーブレットContextListenerインタフェースの実装
/**
 *  Web servlet , servletContextListener 。
 */
@Override
public void contextInitialized(ServletContextEvent sce) {
    //ServletContext servletContext = sce.getServletContext();
    System.out.println(" contextInitialized ");
}

3.実行するメソッドが存在するクラスをspringコンテナでスキャン(@Component)し、実行するメソッドに@PostConstruct注記または静的コードブロックを追加して実行する
@Component
public class Test2 {
    // , 
    static{
        System.out.println("---static--");
    }
    /**
     *  @Postcontruct’ 
     */
    @PostConstruct
    public static void haha(){
        System.out.println("@Postcontruct’ ");
    }
}

4.ApplicationRunnerインタフェースの実装
/**
 *  bean SpringApplication 。 applicationrunner bean
 *  , @order 。
 */
@Override
public void run(ApplicationArguments args) throws Exception {
    System.out.println("ApplicationRunner run ");
}

5.CommandLineRunnerインタフェースの実装
/**
 *  bean SpringApplication 。 commandlinerunner bean, @order 。
 *  applicationArguments , applicationrunner。
 * 
 */
@Override
public void run(String... ) throws Exception {
    System.out.println("CommandLineRunner run ");
}