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.bootgroupId>
      3     <artifactId>spring-boot-devtoolsartifactId>
      4     <scope>runtimescope>
      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(当我没说)


引用:试水流连

转载于:https://www.cnblogs.com/ldy-blogs/p/8671863.html

你可能感兴趣的:(SpringBoot使用devtools导致的类型转换异常)