SpringBoot使用devtools致使的類型轉換異常

  • 遇到的問題:
    SpringBoot項目中的熱部署引起的血的教訓,報錯代碼位置:

      1 XStream xStream1 = new XStream();
      2 xStream1.autodetectAnnotations(true);
      3 xStream1.alias("InterBOSS", InterBossHeader.class);
      4 InterBossHeader resp = (InterBossHeader) xStream1.fromXML(response);
    
    項目中的pom配置:

      1 <dependency>
      2     <groupId>org.springframework.boot</groupId>
      3     <artifactId>spring-boot-devtools</artifactId>
      4     <scope>runtime</scope>
      5 </dependency>
    
  • 問題的分析:
    以上配置發現一樣的類型(InterBossHeader)居然出現了類型轉換異常!WQNMMP—。—
    分析出ClassLoader不一樣致使的類型轉換異常,Spring的dev-tools爲了實現從新裝載class本身實現了一個類加載器,來加載項目中會改變的類,方便重啓時將新改動的內容更新進來,其實其中官方文檔中是有作說明的:

      1 By default, any open project in your IDE will be loaded using the
      2 「restart」 classloader, and any regular .jar file will be loaded using
      3 the 「base」 classloader. If you work on a multi-module project, and not
      4 each module is imported into your IDE, you may need to customize
      5 things. To do this you can create a
      6 META-INF/spring-devtools.properties file.
      7 The spring-devtools.properties file can contain restart.exclude. and
      8 restart.include. prefixed properties. The include elements are items
      9 that should be pulled up into the 「restart」 classloader, and the
     10 exclude elements are items that should be pushed down into the 「base」
     11 classloader. The value of the property is a regex pattern that will be
     12 applied to the classpath.
  • 解決辦法:
    第一種解決方案:在resources目錄下面建立META_INF文件夾,而後建立spring-devtools.properties文件,文件加上相似下面的配置:
    restart.exclude.companycommonlibs=/mycorp-common-[\w-]+.jar
    restart.include.projectcommon=/mycorp-myproj-[\w-]+.jar

    第二種解決方案:不使用spring-boot-devtools(當我沒說)


引用:試水流連spring

相關文章
相關標籤/搜索