Spring Boot 警告:An illegal reflective access operation has occurred

Spring Boot 警告:An illegal reflective access operation has occurred

Spring Boot项目升级到JDK 11,运行时发现警告如下:

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.thoughtworks.xstream.core.util.Fields (file:/C:/Users/pc-bjdev/.m2/repository/com/thoughtworks/xstream/xstream/1.4.11.1/xstream-1.4.11.1.jar) to field java.util.TreeMap.comparator
WARNING: Please consider reporting this to the maintainers of com.thoughtworks.xstream.core.util.Fields
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

解决方案

  • 方案一
    增加 JVM 启动参数:
java --illegal-access=deny

Java 9 中这个参数默认是:permit

  • 方案二

在启动类增加以下方法,亲测试 jdk 11 有效

public static void disableWarning() {
    try {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        Unsafe u = (Unsafe) theUnsafe.get(null);

        Class cls = Class.forName("jdk.internal.module.IllegalAccessLogger");
        Field logger = cls.getDeclaredField("logger");
        u.putObjectVolatile(cls, u.staticFieldOffset(logger), null);
    } catch (Exception e) {
        // ignore
    }
}

启动 Spring Boot 时调用一下上面的方法

public static void main(String[] args) {
    disableWarning(); //禁用警告
    SpringApplication.run(AppApplication.class, args);
}
posted @ 2020-11-24 15:16  趙小傑  阅读(6920)  评论(0编辑  收藏  举报