springboot項目啟動時執行的操作


注解@PostConstruct

使用@PostConstruct注解,該注解是Java5引入,表示項目在啟動時候會執行被該注解修飾的方法。可以在下項目啟動過程中做一些數據的常規化加載,可以加載一些數據庫中的持久化數據到內存中。

@PostConstruct修飾的方法會在加載servlet的時候運行,且只會被執行一次。類似於Servlet的init()方法。被@PostConstruct修飾的方法會在構造方法之后,init()方法之前運行。

類似的注解還有@PreConstruct,被@PreConstruct修飾的方法在服務器卸載Servlet的時候運行,並且只會被服務器調用一次,類似於Servlet的destroy()方法,被@PreConstruct修飾的方法會在destroy()方法之后運行,在Servlet被徹底卸載之前。

整個執行順序如下所示:

  1. 服務器加載Servlet
  2. servlet 構造函數的加載
  3. postConstruct
  4. init(init是在service 中的初始化方法. 創建service 時發生的事件.)
  5. Service
  6. destory
  7. predestory
  8. 服務器卸載serlvet

此外在執行@PostConstruct修飾的方法會在依賴注入完成后被自動調用,即會在 @Autowired依賴注入完成以后,再調用這個方法。

@Component
public class Test {
	@Autowired
	private UserService userService;
	
	@PostConstruct
	public void init(){
		List<User> userList = userService.selectAll();
		for (User user : userList) {
			System.out.println(user.toString());
		}
	}
	// 系統運行結束
	@PreDestroy
    public void destroy(){}
}

如上述代碼所示,比較有意思的一點是如果在Test類中通過@Autowired獲取一個實例,則spring會在運行init()方法之前完成userService的注入。

實現ServletContextAware接口並重寫setServletContext方法

使用此方法時,會在填充完普通Bean的屬性,但是還沒有進行Bean的初始化之前

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

實現ServletContextListener接口

在初始化web應用程序中的任何過濾器或servlet之前,將通知所有servletContexListener上下文初始化。重載contextInitialized方法。重載contextDestroyed方法,在項目運行結束之前進行一些操作。

@Component
public class TestListener implements ServletContextListener {
    /**
     * 在初始化Web應用程序中的任何過濾器或servlet之前,將通知所有servletContextListener上下文初始化。
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) 
        System.out.println("執行contextInitialized方法");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("執行contextDestroyed方法");
    }
}

實現ApplicationRunner接口

用於指示bean包含在SpringApplication中應運行的接口,可以定義多個application bean ,在同一應用程序上下文中,可以使用有序接口或@order注解進行排序

  @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner的run方法");
    }

實現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