一、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
办法
@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);
}
}
三、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 Specification
- JAR (file format)
SpringBoot的jar包,会有3个文件夹:
- BOOT-INF:寄存自己编写并编译好的 .class 文件和静态资源文件、配置文件等
- META-INF:有一个
MANIFEST.MF
的文件 - org:
spring-boot-loader
的一些 .class 文件
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
- 在
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 办法,引导发动即可。