java.lang.ClassCastException: DTOObject cannot be cast to DTOObject

岁酱吖の 提交于 2019-12-05 17:42:21

When you use DevTools with caching, you need to be aware of this limitation.

When the object is serialized into the cache, the application class loader is C1. Then after you change some code/configuration, devtools automatically restart the context and creates a new classloader (C2). When you hit that cache method, the cache abstraction finds an entry in the cache and it deserializes it from the store. If the cache library doesn't take the context classloader into account, that object will have the wrong classloader attached to it (which explains that weird exception A cannot be cast to A).

TL;DR do not serialize classes with devtools if the cache library doesn't use the context classloader. Or put your cache library in the application classloader:

restart.include.yourcache=/my-cache-lib-[\\w-]+\.jar

I actually tried the proposed solution (and many variations thereof) with no luck. E.g., this didn't stop the problem from occurring:

restart.include.cache=/spring-data-redis-.*.jar

I updated the above to callout the specific version I was using and it still didn't work.

What I ended up doing which did work was to exclude spring-boot-devtools from my project. I'm using Maven so the annotation was this:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <version>[1.5.9,)</version>
        <scope>provided</scope>
    </dependency>

This will prevent any version equal to or greater than 1.5.9 from loading up. After I included the above, everything worked as expected. I know this isn't an ideal solution for all, but I made little use of the restart functions of devtools so this was actually a good approach for me.

I am using Spring Boot 2.0.5, and I ended up removing devtools altogether from pom.xml. Thanks to the answer above from @Always Learning.
As much as I hate to do this, but I can't find another way for now!

  <!-- 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
     -->    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!