URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
URLClassLoader urlClassLoader = new URLClassLoader(classLoader.getURLs(), null);
//TODO 一定要設置線程上下文類加載器,因爲Spring Boot 在加載一些類的使用的就是這個線程上下文類加載器,而默認的線程上下文類加載器等於ClassLoader.getSystemClassLoader(),如果兩個類加載器加載同一個類文件就會認爲是兩個類,會無法賦值,Spring Boot也起不來
Thread.currentThread().setContextClassLoader(urlClassLoader);
Class<?> aClass = urlClassLoader.loadClass("com.beiding.hotel.Application");
Method main = aClass.getMethod("main", String[].class);
main.invoke(null, (Object) new String[0]);
Spring Boot 組件掃描原理
//掃描方法
org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan
//尋找類資源
org.springframework.core.io.support.PathMatchingResourcePatternResolver.getResources
org.springframework.core.io.support.PathMatchingResourcePatternResolver.doFindAllClassPathResources
findPathMatchingResources
基本邏輯:
1. 首先解析出來需要掃描的 package
2. 根據package確定資源的相對路徑 例如 : com.beiding 相對路徑爲 com/beiding/
3. 使用給定的類加載器的 getResources 方法 獲取 上述步驟解析出來的相對路徑,獲取URL對象
4. 判斷上述過程獲取的URL是jar包還是其他
如果是jar 就調用 doFindPathMatchingJarResources 獲取jar包中的資源
如果是文件夾 就調用 doFindPathMatchingFileResources 掃描.class文件