Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring 容器啟動完成後自動執行一段邏輯

開發時常會遇到這樣的需求:專案一啟動,就自動開啟某個服務或預先載入一批資料。若專案由 Spring 管理,最乾淨的做法是監聽容器刷新完成的事件,而不是在不知情的情況下急著使用 Bean。

為什麼會出現空指標

很多人直覺地在某個類別的建構階段就把事情做完,結果執行時丟出 NullPointerException。原因在於:這個類別本身或許已完成初始化,但它依賴的其他類別(有時是更深層的關聯物件)還沒就位。與其猜測順序,不如把觸發時機交給容器。

解法:監聽 ContextRefreshedEvent

思路只有兩步:

  1. 寫一個類別實作 ApplicationListener<ContextRefreshedEvent>,監聽容器初始化完成事件。
  2. 把它交給 Spring 管理,可以用傳統的 <bean> 宣告,也可以直接標上 @Service。

實作

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

@Service
public class StartAddDataListener implements ApplicationListener<ContextRefreshedEvent>
{
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event)
    {
        if (event.getApplicationContext().getParent() == null)
        {
            // 根容器沒有 parent,確保邏輯只執行一次
            System.out.println("加載了");
        }

        // 另一種等價寫法
        if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext"))
        {
            System.out.println("加載一次的");
        }
    }
}

加上 parent 判斷(或比對 displayName)很重要:在 Spring MVC 環境中通常存在父子兩個容器,不做過濾的話事件會被觸發兩次。

別忘了掃描套件

在 applicationContext-servlet.xml 中設定要掃描的路徑,並明確指定要註冊的註解:

<context:component-scan base-package="com.test.controller" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>

部署啟動後,容器初始化完成的瞬間就會看到自訂的輸出。

延伸:component-scan 的過濾機制

component-scan 預設會掃描指定路徑(含所有子層級)下的套件,把標註 @Component、@Repository、@Service、@Controller 的類別自動註冊為 Bean;同時也讓 @Required、@Autowired、@PostConstruct、@PreDestroy、@Resource 等註解生效(這部分等於 annotation-config 的作用)。

若需要更細的控制,可以搭配兩個過濾器:

  • context:exclude-filter:排除被特定標註標記的類別。
  • context:include-filter:只載入被特定標註標記的類別。

典型的分工是:主容器(applicationContext.xml)排除 @Controller,交給 Spring MVC 的設定檔處理;而 Spring MVC 設定檔則只載入 @Controller,排除 @Service。

<context:component-scan base-package="com">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

如果你使用的是 Spring Boot 或較新版本,也可以直接實作 ApplicationRunner 或 CommandLineRunner,或在方法上標註 @EventListener 搭配 ApplicationReadyEvent,語意會更清楚。

Copyright © Linux教程網 All Rights Reserved