Springboot啟動前執行方法


1.實現ServletContextAware接口並重寫其setServletContext方法

@Component
public class TestStarted implements ServletContextAware {
    /**
     * 在填充普通bean屬性之后但在初始化之前調用
     * 類似於initializingbean的afterpropertiesset或自定義init方法的回調
     *
     */
    @Override
    public void setServletContext(ServletContext servletContext) {
        System.out.println("setServletContext方法");
    }
}

注意:該方法會在填充完普通Bean的屬性,但是還沒有進行Bean的初始化之前執行

2.實現ServletContextListener接口

/**
 * 在初始化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方法");
}

來源:https://www.cnblogs.com/lsgspace/p/10508180.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM