一、jar包和war包的区别1.1 war包

war包是Java Web应用程序的一种打包方式符合Servlet标准,它是Web Archive的缩写,主要用于存储Web应用程序相关的文件,包括Java类文件、JSP、HTML、CSS、JavaScript、图片等资源文件。war包需要部署到web服务器中(Tomcat、Apache、IIS)

1.2 jar包

jar包是类的归档文件,主要用于存储Java类文件和相关资源文件。它通常被用于封装Java应用程序或Java类库,方便程序的部署和发布jar包可以被JVM直接加载和运行。

1.3 主要区别:

jar包主要用于存储Java类文件和相关资源文件,而war包主要用于存储Web应用程序相关的文件。jar包可以被JVM直接加载和运行,而war包需要被Web服务器加载和运行。jar包通常用于封装Java应用程序或Java类库,而war包用于封装Java Web应用程序。

二、SpringBoot使用war包启动war包启动:需要先启动外部的Web服务器,实现Servlet3.0规范中引导应用启动类,然后将war包放入Web服务器下,Web服务器通过回调引导应用启动类方法启动应用。2.1 Servlet3.0规范中引导应用启动的说明

在Servlet容器(Tomcat、Jetty等)启动应用时,会扫描应用jar包中 ServletContainerInitializer 的实现类。框架必须在jar包的 META-INF/services 的文件夹中提供一个名为 javax.servlet.ServletContainerInitializer 的文件,文件内容要写明 ServletContainerInitializer 的实现类的全限定名。这个 ServletContainerInitializer 是一个接口,实现它的类必须实现一个方法:onStartUp可以在这个 ServletContainerInitializer 的实现类上标注 @HandlesTypes 注解,在应用启动的时候自行加载一些附加的类,这些类会以字节码的集合形式传入 onStartup 方法的第一个参数中。

public interface ServletContainerInitializer {

void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException;

}复制代码2.2 SpringBootServletInitializer的作用和原理Spirng中SpringServletContainerInitializer实现了Servlet的规范

图片

@HandlesTypes(WebApplicationInitializer.class)public class SpringServletContainerInitializer implements ServletContainerInitializer {

@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
        throws ServletException {
    // SpringServletContainerInitializer会加载所有的WebApplicationInitializer类型的普通实现类

    List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();

    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方法@Overridepublic 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);

}}复制代码三、SpringBoot使用jar包启动按照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 SpecificationJAR (file format)

SpringBoot的jar包,会有3个文件夹:

BOOT-INF:存放自己编写并编译好的 .class 文件和静态资源文件、配置文件等META-INF:有一个 MANIFEST.MF 的文件org:spring-boot-loader 的一些 .class 文件

图片

META-INF 下面的 MANIFEST.MF 文件,里面的内容如下:Manifest-Version: 1.0Spring-Boot-Classpath-Index: BOOT-INF/classpath.idxImplementation-Title: my-small-testImplementation-Version: 1.0-SNAPSHOTSpring-Boot-Layers-Index: BOOT-INF/layers.idxStart-Class: com.small.test.SpringBootDemoApplicationSpring-Boot-Classes: BOOT-INF/classes/Spring-Boot-Lib: BOOT-INF/lib/Build-Jdk-Spec: 1.8Spring-Boot-Version: 2.4.0Created-By: Maven Jar Plugin 3.2.0Main-Class: org.springframework.boot.loader.JarLauncher复制代码

在 Start-Class 中注明了 SpringBoot 的主启动类在 Main-Class 中注明了一个类: 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);

}复制代码3.1 registerUrlProtocolHandler:注册URL协议并清除应用缓存先设置当前系统的一个变量 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
    }
}

复制代码3.2createClassLoader:设置类加载路径 protected ClassLoader createClassLoader(Iterator<Archive> archives) throws Exception {

List<URL> urls = new ArrayList<>(50);
while (archives.hasNext())
  urls.add(((Archive)archives.next()).getUrl()); 
return createClassLoader(urls.<URL>toArray(new URL[0]));

}复制代码 protected ClassLoader createClassLoader(URL[] urls) throws Exception {

return new LaunchedURLClassLoader(isExploded(), getArchive(), urls, getClass().getClassLoader());

}复制代码3.3 执行main方法 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 方法,引导启动即可。

作者:|视角线|,原文链接: https://segmentfault.com/a/1190000043561013

文章推荐

JavaWeb 中 Filter过滤器

Java并发(四)----线程运行原理

理解Java程序的执行

Midjourney:一步一步教你如何使用 AI 绘画 MJ

KMeans算法与GMM混合高斯聚类

NodeJs的模块化和包

从数据库获取数据转成json格式-java后端

Markdown 利用HTML进行优雅排版

细说React组件性能优化

Matlab常用图像处理命令108例(三)

Vue—关于实例中为什么只能有一个根元素?

使用nvm安装以及管理多版本node教程