spring-boot-devtools 不同ClassLoader引起的问题

在Spring Boot的文档spring-boot-devtools 部分,有如下的 描述:

By default, any open project in your IDE will be loaded using the
“restart” classloader, and any regular .jar file will be loaded using
the “base” classloader. If you work on a multi-module project, and not
each module is imported into your IDE, you may need to customize
things. To do this you can create a
META-INF/spring-devtools.properties file.
The spring-devtools.properties file can contain restart.exclude. and
restart.include. prefixed properties. The include elements are items
that should be pulled up into the “restart” classloader, and the
exclude elements are items that should be pushed down into the “base”
classloader. The value of the property is a regex pattern that will be
applied to the classpath.

我遇到的问题是向上转型时出现ClassCastException,按说向上转型是不会出现这个问题的,于是想到可能是ClassLoader不一样导致的,打印了两个对象的ClassLoader,确实不同,一个RestartClassLoader,一个普通的AppClassLoader。

解决方案就是在resources目录下面创建META_INF文件夹,然后创建spring-devtools.properties文件,文件加上类似下面的配置:

restart.exclude.companycommonlibs=/mycorp-common-[\\w-]+\.jar
restart.include.projectcommon=/mycorp-myproj-[\\w-]+\.jar

然额!不知道是不是我姿势不太对,怎么研究也没弄出来!

所以就想了个折中的方法

 public static User getUser()
    {
    	Object obj = getSubjct().getPrincipal();
    	User user = new User();
    	if(obj instanceof User) {
    		user = (User) obj;
    	} else {
    		user = JSON.parseObject(JSON.toJSON(obj).toString(), User.class);
    	}
//        return (User) getSubjct().getPrincipal();
    	return user;
    }
   

或者使用这种方法,个人感觉更方便

 Object obj =subject.getPrincipal();
        User user=new User();
        BeanUtils.copyProperties(obj,user);

————————————————
版权声明:本文为CSDN博主「miraku」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/jyxswt/article/details/80601787
参考地址:https://blog.csdn.net/andwey/article/details/106053195?utm_medium=distribute.pc_relevant.none-task-blog-baidujs-5

猜你喜欢

转载自blog.csdn.net/weixin_43897590/article/details/105914681
今日推荐