Spring 掃描不到註解

Spring 掃描不到註解

問題現象

項目中使用瞭如下配置,進行掃描。

<ctx:component-scan base-package="com.li.test.rs"/>

但是開發環境中無論如何無法正常掃描到註解類,而生產環境沒有此問題。

問題原因

原因很簡單,開發環境中項目所在路徑中存在空格,所以造成此問題。

原因定位及剖析

  1. 首先打開Spring的debug級別日誌,發現日誌中有如下輸出:

    [org.springframework.core.io.support.PathMatchingResourcePatternResolver::retrieveMatchingFiles] Skipping [F:\from%20SVN\xx\xx\xx\xx\xx\com\li\test\rs] because it does not exist
  2. 查看對應源碼可以找到如下內容:

    if (!rootDir.exists()) {
    // Silently skip non-existing directories.
    if (logger.isDebugEnabled()) {
        logger.debug("Skipping [" + rootDir.getAbsolutePath() + "] because it does not exist");
    }
    return Collections.emptySet();
    }
  3. 繼續查看源碼,我們可以定位到rootDir的值初始來源於ClassLoader的findResources,該方法返回的是可枚舉的URL對象。

  4. 進行如下測試(在項目的classes目錄下創建了com/l j目錄):

       public static void main(String[] args) throws Exception
       {
           Enumeration<URL> urls = Test.class.getClassLoader().getResources("com/l j/");
           String aa = null;
           while(urls.hasMoreElements()){
               aa = urls.nextElement().getFile();
           }
           String bb = aa.substring(1);
           File file = new File(bb);
           System.out.println("File path is " + file.getAbsolutePath());
           System.out.println("File exist " + file.exists());
           File file1 = new File(bb.replace("%20", " "));
           System.out.println("File1 path is " + file1.getAbsolutePath());
           System.out.println("File1 exist " + file1.exists());
       }
    

    輸出爲:

    File path is D:\workapace\cc\MyTest\build\classes\com\l%20j
    File exist false
    File1 path is D:\workapace\cc\MyTest\build\classes\com\l j
    File1 exist true
  5. 至此問題已經很明顯了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章