最近搭建项目的时候想要配置一个热部署,所以依赖了devtools,也就顺便进了devtools的坑。
问题发现的起因是因为想要在启动类加一些启动验证,这时候发现验证会执行两次。
2022-08-25 18:21:08: INFO [main] c.e.c.c.l .java:29 - oswindows 7
2022-08-25 18:21:08: INFO [main] c.e.c.c.l .java:32 - This is windows
2022-08-25 18:21:09: INFO [restartedMain] c.e.c.c.l.v.VerifyBeforeStartUp
2022-08-25 18:21:09: INFO [restartedMain] c.e.c.c.l.u.SystemTool SystemTool.java:29 - oswindows 7
发现验证方法会被执行两次。一次是线程mian,另外一次是线程restartedMain。
通过查询资料发现是因为热部署插件devtools引起的。猜测可能的原因是类加载器不同导致的。
解决方案:
try {
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
Class<?> aClass = systemClassLoader.loadClass("com.a.b.c.ConnectionPool");
Method getInstance = MethodUtils.getMatchingMethod(aClass, "getInstance");
ConnectionPool invoke = (ConnectionPool)getInstance.invoke(null);
System.out.println(aClass);
System.out.println(aClass.getClassLoader());
}catch (Exception e) {
e.printStackTrace();
}