1. 程式人生 > >SpringBoot使用devtools導致的類型轉換異常

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

libs boot ont hat create 自己 res tar art

  • 遇到的問題:
    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(當我沒說)


引用:試水流連

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