war包启动:需要先启动外部的Web服务器,实现Servlet3.0规范中引导应用启动类,然后将war包放入Web服务器下,Web服务器通过回调引导应用启动类方法启动应用。
public interface ServletContainerInitializer { void onStartup(Set> c, ServletContext ctx) throws ServletException; } 复制代码
Spirng中SpringServletContainerInitializer实现了Servlet的规范
@HandlesTypes(WebApplicationInitializer.class) public class SpringServletContainerInitializer implements ServletContainerInitializer { @Override public void onStartup(Set> webAppInitializerClasses, ServletContext servletContext) throws ServletException { // SpringServletContainerInitializer会加载所有的WebApplicationInitializer类型的普通实现类 List initializers = new LinkedList (); if (webAppInitializerClasses != null) { for (Class> waiClass : webAppInitializerClasses) { // 如果不是接口,不是抽象类 if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) { try { // 创建该类的实例 initializers.add((WebApplicationInitializer) waiClass.newInstance()); } catch (Throwable ex) { throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex); } } } } if (initializers.isEmpty()) { servletContext.log("No Spring WebApplicationInitializer types detected on classpath"); return; } servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath"); AnnotationAwareOrderComparator.sort(initializers); // 启动Web应用onStartup方法 for (WebApplicationInitializer initializer : initializers) { initializer.onStartup(servletContext); } } } 复制代码
@HandlesTypes使用BCEL的ClassParser在字节码层面读取了/WEB-INF/classes和jar中class文件的超类名和实现的接口名,判断是否与记录的注解类名相同,若相同再通过org.apache.catalina.util.Introspection类加载为Class对象保存起来,最后传入onStartup方法参数中
SpringServletContainerInitializer类上标注了@HandlesTypes(WebApplicationInitializer.class),所以会导入WebApplicationInitializer实现类
SpringBoot中SpringBootServletInitializer是WebApplicationInitializer的抽象类,实现了onStartup方法
@Override public void onStartup(ServletContext servletContext) throws ServletException { // Logger initialization is deferred in case an ordered // LogServletContextInitializer is being used this.logger = LogFactory.getLog(getClass()); // 创建 父IOC容器 WebApplicationContext rootAppContext = createRootApplicationContext(servletContext); if (rootAppContext != null) { servletContext.addListener(new ContextLoaderListener(rootAppContext) { @Override public void contextInitialized(ServletContextEvent event) { // no-op because the application context is already initialized } }); } else { this.logger.debug("No ContextLoaderListener registered, as " + "createRootApplicationContext() did not " + "return an application context"); } } 复制代码
创建父容器
protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) { // 使用Builder机制,前面也介绍过 SpringApplicationBuilder builder = createSpringApplicationBuilder(); builder.main(getClass()); ApplicationContext parent = getExistingRootWebApplicationContext(servletContext); if (parent != null) { this.logger.info("Root context already created (using as parent)."); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null); builder.initializers(new ParentContextApplicationContextInitializer(parent)); } // 设置Initializer builder.initializers(new ServletContextApplicationContextInitializer(servletContext)); // 在这里设置了容器启动类:AnnotationConfigServletWebServerApplicationContext builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class); // 【引导】多态进入子类(自己定义)的方法中 builder = configure(builder); builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext)); // builder.build(),创建SpringApplication SpringApplication application = builder.build(); if (application.getAllSources().isEmpty() && AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) { application.addPrimarySources(Collections.singleton(getClass())); } Assert.state(!application.getAllSources().isEmpty(), "No SpringApplication sources have been defined. Either override the " + "configure method or add an @Configuration annotation"); // Ensure error pages are registered if (this.registerErrorPageFilter) { application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class)); } // 启动SpringBoot应用 return run(application); } 复制代码
所以我们只需要自定义类继承SpringBootServletInitializer并实现configure方法告诉启动类所在的位置就可以实现SpringBoot自启动了
例如:
public class MyInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { //MySpringBootApplication为SpingBoot启动类 return application.sources(MySpringBootApplication.class); } } 复制代码
按照java官方文档规定,java -jar命令引导的具体启动类必须配置在MANIFEST.MF中的Main-class属性中,该值代表应用程序执行入口类也就是包含main方法的类。
从MANIFEST.MF文件内容可以看到,Main-Class这个属性定义了org.springframework.boot.loader.JarLauncher,JarLauncher就是对应Jar文件的启动器。而我们项目的启动类SpringBootDemoApplication定义在Start-Class属性中,
JarLauncher会将BOOT-INF/classes下的类文件和BOOT-INF/lib下依赖的jar加入到classpath下,然后调用META-INF/MANIFEST.MF文件Start-Class属性完成应用程序的启动。
关于 jar 官方标准说明请移步
- JAR File Specification
- JAR (file format)
SpringBoot的jar包,会有3个文件夹:
META-INF 下面的 MANIFEST.MF 文件,里面的内容如下:
Manifest-Version: 1.0 Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx Implementation-Title: my-small-test Implementation-Version: 1.0-SNAPSHOT Spring-Boot-Layers-Index: BOOT-INF/layers.idx Start-Class: com.small.test.SpringBootDemoApplication Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ Build-Jdk-Spec: 1.8 Spring-Boot-Version: 2.4.0 Created-By: Maven Jar Plugin 3.2.0 Main-Class: org.springframework.boot.loader.JarLauncher 复制代码
package org.springframework.boot.loader; import java.io.IOException; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.springframework.boot.loader.archive.Archive; public class JarLauncher extends ExecutableArchiveLauncher { private static final String DEFAULT_CLASSPATH_INDEX_LOCATION = "BOOT-INF/classpath.idx"; static final Archive.EntryFilter NESTED_ARCHIVE_ENTRY_FILTER; static { NESTED_ARCHIVE_ENTRY_FILTER = (entry -> entry.isDirectory() ? entry.getName().equals("BOOT-INF/classes/") : entry.getName().startsWith("BOOT-INF/lib/")); } public JarLauncher() {} protected JarLauncher(Archive archive) { super(archive); } protected ClassPathIndexFile getClassPathIndex(Archive archive) throws IOException { if (archive instanceof org.springframework.boot.loader.archive.ExplodedArchive) { String location = getClassPathIndexFileLocation(archive); return ClassPathIndexFile.loadIfPossible(archive.getUrl(), location); } return super.getClassPathIndex(archive); } private String getClassPathIndexFileLocation(Archive archive) throws IOException { Manifest manifest = archive.getManifest(); Attributes attributes = (manifest != null) ? manifest.getMainAttributes() : null; String location = (attributes != null) ? attributes.getValue("Spring-Boot-Classpath-Index") : null; return (location != null) ? location : "BOOT-INF/classpath.idx"; } protected boolean isPostProcessingClassPathArchives() { return false; } protected boolean isSearchCandidate(Archive.Entry entry) { return entry.getName().startsWith("BOOT-INF/"); } protected boolean isNestedArchive(Archive.Entry entry) { return NESTED_ARCHIVE_ENTRY_FILTER.matches(entry); } public static void main(String[] args) throws Exception { (new JarLauncher()).launch(args); } } 复制代码
父类Launcher#launch
protected void launch(String[] args) throws Exception { if (!isExploded()) //3.1 注册URL协议并清除应用缓存 JarFile.registerUrlProtocolHandler(); //3.2 设置类加载路径 ClassLoader classLoader = createClassLoader(getClassPathArchivesIterator()); String jarMode = System.getProperty("jarmode"); String launchClass = (jarMode != null && !jarMode.isEmpty()) ? "org.springframework.boot.loader.jarmode.JarModeLauncher" : getMainClass(); //3.3 执行main方法 launch(args, launchClass, classLoader); } 复制代码
先设置当前系统的一个变量 java.protocol.handler.pkgs,而这个变量的作用,是设置 URLStreamHandler 实现类的包路径。
之后要重置缓存,目的是清除之前启动的残留。
private static final String MANIFEST_NAME = "META-INF/MANIFEST.MF"; private static final String PROTOCOL_HANDLER = "java.protocol.handler.pkgs"; private static final String HANDLERS_PACKAGE = "org.springframework.boot.loader"; public static void registerUrlProtocolHandler() { String handlers = System.getProperty(PROTOCOL_HANDLER, ""); System.setProperty(PROTOCOL_HANDLER, ("".equals(handlers) ? HANDLERS_PACKAGE : handlers + "|" + HANDLERS_PACKAGE)); resetCachedUrlHandlers(); } // 重置任何缓存的处理程序,以防万一已经使用了jar协议。 // 我们通过尝试设置null URLStreamHandlerFactory来重置处理程序,除了清除处理程序缓存之外,它应该没有任何效果。 private static void resetCachedUrlHandlers() { try { URL.setURLStreamHandlerFactory(null); } catch (Error ex) { // Ignore } } 复制代码
protected ClassLoader createClassLoader(Iterator archives) throws Exception { Listurls = new ArrayList<>(50); while (archives.hasNext()) urls.add(((Archive)archives.next()).getUrl()); return createClassLoader(urls. toArray(new URL[0])); } 复制代码
protected ClassLoader createClassLoader(URL[] urls) throws Exception { return new LaunchedURLClassLoader(isExploded(), getArchive(), urls, getClass().getClassLoader()); } 复制代码
protected void launch(String[] args, String launchClass, ClassLoader classLoader) throws Exception { Thread.currentThread().setContextClassLoader(classLoader); createMainMethodRunner(launchClass, args, classLoader).run(); } 复制代码
protected MainMethodRunner createMainMethodRunner(String mainClass, String[] args, ClassLoader classLoader) { return new MainMethodRunner(mainClass, args); } 复制代码
package org.springframework.boot.loader; import java.lang.reflect.Method; public class MainMethodRunner { private final String mainClassName; private final String[] args; public MainMethodRunner(String mainClass, String[] args) { this.mainClassName = mainClass; this.args = (args != null) ? (String[])args.clone() : null; } public void run() throws Exception { Class> mainClass = Class.forName(this.mainClassName, false, Thread.currentThread().getContextClassLoader()); //获取主启动类的main方法 Method mainMethod = mainClass.getDeclaredMethod("main", new Class[] { String[].class }); mainMethod.setAccessible(true); //执行main方法 mainMethod.invoke((Object)null, new Object[] { this.args }); } } 复制代码
所以 SpringBoot 应用在开发期间只需要写 main 方法,引导启动即可。