十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
前言
成都创新互联公司于2013年开始,公司以网站建设、成都做网站、系统开发、网络推广、文化传媒、企业宣传、平面广告设计等为主要业务,适用行业近百种。服务企业客户成百上千家,涉及国内多个省份客户。拥有多年网站建设开发经验。为企业提供专业的网站建设、创意设计、宣传推广等服务。 通过专业的设计、独特的风格,为不同客户提供各种风格的特色服务。
在学习SparkJava、Vert.x等轻量级Web框架的时候,都遇到过打包问题,这两个框架打包的时候都需要添加额外的Maven配置,并指定启动类才能得到可执行的JAR包;
而springboot项目,似乎都不需要额外的配置,直接package就可以得到可执行的JAR包,这是怎么回事呢?
Vert.x要怎么配?
我们先来看看,Vert.x打包做哪些配置
1)引入maven-shade-plugin插件
2)在插件中指定在package完成时触发shade操作
3)指定启动类
maven-shade-plugin 3.1.0 package shade com.test.Starter
效果:
执行package操作后,将得到两个jar包
①origin-[your project].jar(Maven默认打包操作得到的jar包,该包仅包含此项目的类)
②[your project].jar(带有依赖包,且配置有启动类的可执行JAR包)
Spring Boot又是怎么做的
不用添加插件?=> 初始化时默认就有
Spring Boot 初始化得到的项目中,默认带有spring-boot-maven-plugin的Maven配置
SpringBoot打包的基本原理与前面的Vertx配置相同,都是使用maven-shade-plugin(spring-boot-maven-plugin底层使用maven-shade-plugin),在package完成之后,加入依赖的包,并指定启动类。
SpringBoot是在package时,触发repackage,将原打包结果重命名为[your project].jar.original,并得到带有依赖包和配置好启动类的[your project].jar
不用指定启动类?=> 默认扫描得到启动类
spring-boot-maven-plugin会扫描项目,并以带有@SpringBootApplication注解和main方法的类作为启动类。
默认情况下,SpringBoot项目默认启动类写死JarLauncher,该类的main方法再调用扫描得到的实际启动类(XXXApplication)的main方法
源码查看
我们从maven repository下载一个spring-boot-maven-plugin的源码进行查看,查看RepackageMojo.java。
从@Mojo注解中,我们可以知道,该Mojo绑定在PACKAGE(注解中的defaultPhase=LifecyclePhase.PACKAGE),即在package完成后触发
/**
* Repackages existing JAR and WAR archives so that they can be executed from the command
* line using {@literal java -jar}. With layout=NONE
can also be used simply
* to package a JAR with nested dependencies (and no main class, so not executable).
*
* @author Phillip Webb
* @author Dave Syer
* @author Stephane Nicoll
* @author Björn Lindström
* @since 1.0.0
*/
@Mojo(name = "repackage", defaultPhase = LifecyclePhase.PACKAGE, requiresProject = true, threadSafe = true,
requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME,
requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME)
public class RepackageMojo extends AbstractDependencyFilterMojo {
//...
}
我们可以看到,该Mojo中可以指定一个mainclass作为启动类,但是如果没有指定的时候,它是如何处理的呢?
/** * The name of the main class. If not specified the first compiled class found that * contains a 'main' method will be used. * @since 1.0.0 */ @Parameter private String mainClass;
我们跟踪这个mainClass,发现在此类中,没有对这个mainClass进行赋值的操作,只用来构造一个Repackager(也就是说在该Maven插件没有配置mainClass的时候,传给Repackager的就是一个null),我们观察到这个Repackager就是该Mojo执行
@Override public void execute() throws MojoExecutionException, MojoFailureException { if (this.project.getPackaging().equals("pom")) { getLog().debug("repackage goal could not be applied to pom project."); return; } if (this.skip) { getLog().debug("skipping repackaging as per configuration."); return; } repackage(); } private void repackage() throws MojoExecutionException { Artifact source = getSourceArtifact(); File target = getTargetFile(); Repackager repackager = getRepackager(source.getFile()); Setartifacts = filterDependencies(this.project.getArtifacts(), getFilters(getAdditionalFilters())); Libraries libraries = new ArtifactsLibraries(artifacts, this.requiresUnpack, getLog()); try { LaunchScript launchScript = getLaunchScript(); repackager.repackage(target, libraries, launchScript); //执行repackage操作 } catch (IOException ex) { throw new MojoExecutionException(ex.getMessage(), ex); } updateArtifact(source, target, repackager.getBackupFile()); } private Repackager getRepackager(File source) { Repackager repackager = new Repackager(source, this.layoutFactory); repackager.addMainClassTimeoutWarningListener(new LoggingMainClassTimeoutWarningListener()); repackager.setMainClass(this.mainClass); //将插件配置的mainClass注入,默认就是null if (this.layout != null) { getLog().info("Layout: " + this.layout); repackager.setLayout(this.layout.layout()); } return repackager; }
由上可知,mainClass的最终确定,应该在Repackager的中完成,我继续跟踪该代码(Repackager来自spring-boot-maven-plugin下引入的spring-boot-loader-tools),打开Repackager的代码。我们观察到Repackager的setMainClass并没有做额外的操作,只是将传入的参数set进来,但是从注释中可以得知,其在使用时如果为空,则会搜索合适的类作为MainClass
/** * Utility class that can be used to repackage an archive so that it can be executed using * '{@literal java -jar}'. * * @author Phillip Webb * @author Andy Wilkinson * @author Stephane Nicoll * @since 1.0.0 */ public class Repackager { //... /** * Sets the main class that should be run. If not specified the value from the * MANIFEST will be used, or if no manifest entry is found the archive will be * searched for a suitable class. * @param mainClass the main class name */ public void setMainClass(String mainClass) { this.mainClass = mainClass; } //... }
我们就从上面调用repackage方法开始看
/** * Repackage to the given destination so that it can be launched using ' * {@literal java -jar}'. * @param destination the destination file (may be the same as the source) * @param libraries the libraries required to run the archive * @param launchScript an optional launch script prepended to the front of the jar * @throws IOException if the file cannot be repackaged * @since 1.3.0 */ public void repackage(File destination, Libraries libraries, LaunchScript launchScript) throws IOException { if (destination == null || destination.isDirectory()) { throw new IllegalArgumentException("Invalid destination"); } if (libraries == null) { throw new IllegalArgumentException("Libraries must not be null"); } if (this.layout == null) { this.layout = getLayoutFactory().getLayout(this.source); } destination = destination.getAbsoluteFile(); File workingSource = this.source; if (alreadyRepackaged() && this.source.equals(destination)) { return; } if (this.source.equals(destination)) { workingSource = getBackupFile(); workingSource.delete(); renameFile(this.source, workingSource); } destination.delete(); try { try (JarFile jarFileSource = new JarFile(workingSource)) { repackage(jarFileSource, destination, libraries, launchScript); //这里往下查看 } } finally { if (!this.backupSource && !this.source.equals(workingSource)) { deleteFile(workingSource); } } } private void repackage(JarFile sourceJar, File destination, Libraries libraries, LaunchScript launchScript) throws IOException { WritableLibraries writeableLibraries = new WritableLibraries(libraries); try (JarWriter writer = new JarWriter(destination, launchScript)) { writer.writeManifest(buildManifest(sourceJar)); //注意这里有一个buildManifest writeLoaderClasses(writer); if (this.layout instanceof RepackagingLayout) { writer.writeEntries(sourceJar, new RenamingEntryTransformer(((RepackagingLayout) this.layout).getRepackagedClassesLocation()), writeableLibraries); } else { writer.writeEntries(sourceJar, writeableLibraries); } writeableLibraries.write(writer); } } private Manifest buildManifest(JarFile source) throws IOException { Manifest manifest = source.getManifest(); if (manifest == null) { manifest = new Manifest(); manifest.getMainAttributes().putValue("Manifest-Version", "1.0"); } manifest = new Manifest(manifest); String startClass = this.mainClass; //mainClass if (startClass == null) { startClass = manifest.getMainAttributes().getValue(MAIN_CLASS_ATTRIBUTE); //先尝试从mainfest中拿,这个暂时不清楚数据来源 } if (startClass == null) { startClass = findMainMethodWithTimeoutWarning(source); //这里触发搜索mainClass } String launcherClassName = this.layout.getLauncherClassName(); if (launcherClassName != null) { manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE, launcherClassName); if (startClass == null) { throw new IllegalStateException("Unable to find main class"); } manifest.getMainAttributes().putValue(START_CLASS_ATTRIBUTE, startClass); } else if (startClass != null) { manifest.getMainAttributes().putValue(MAIN_CLASS_ATTRIBUTE, startClass); } String bootVersion = getClass().getPackage().getImplementationVersion(); manifest.getMainAttributes().putValue(BOOT_VERSION_ATTRIBUTE, bootVersion); manifest.getMainAttributes().putValue(BOOT_CLASSES_ATTRIBUTE, (this.layout instanceof RepackagingLayout) ? ((RepackagingLayout) this.layout).getRepackagedClassesLocation() : this.layout.getClassesLocation()); String lib = this.layout.getLibraryDestination("", LibraryScope.COMPILE); if (StringUtils.hasLength(lib)) { manifest.getMainAttributes().putValue(BOOT_LIB_ATTRIBUTE, lib); } return manifest; } private String findMainMethodWithTimeoutWarning(JarFile source) throws IOException { long startTime = System.currentTimeMillis(); String mainMethod = findMainMethod(source); //这里往下看 long duration = System.currentTimeMillis() - startTime; if (duration > FIND_WARNING_TIMEOUT) { for (MainClassTimeoutWarningListener listener : this.mainClassTimeoutListeners) { listener.handleTimeoutWarning(duration, mainMethod); } } return mainMethod; } protected String findMainMethod(JarFile source) throws IOException { return MainClassFinder.findSingleMainClass(source, this.layout.getClassesLocation(), SPRING_BOOT_APPLICATION_CLASS_NAME); //在指定Jar文件中查找MainClass } private static final String SPRING_BOOT_APPLICATION_CLASS_NAME = "org.springframework.boot.autoconfigure.SpringBootApplication"; /** * Find a single main class in a given jar file. A main class annotated with an * annotation with the given {@code annotationName} will be preferred over a main * class with no such annotation. * @param jarFile the jar file to search * @param classesLocation the location within the jar containing classes * @param annotationName the name of the annotation that may be present on the main * class * @return the main class or {@code null} * @throws IOException if the jar file cannot be read */ public static String findSingleMainClass(JarFile jarFile, String classesLocation, String annotationName) throws IOException { SingleMainClassCallback callback = new SingleMainClassCallback(annotationName); MainClassFinder.doWithMainClasses(jarFile, classesLocation, callback); return callback.getMainClassName(); }
从最后几步中,我们可以知道,查找的mainClass是一个带有@SpringBootApplication注解的类。不用说明,该类肯定是带有main方法,如果你想进一步确认,则可以继续查看MainClassFinder的代码(来自spring-boot-loader-tools)。
//... private static final Type MAIN_METHOD_TYPE = Type.getMethodType(Type.VOID_TYPE, STRING_ARRAY_TYPE); private static final String MAIN_METHOD_NAME = "main"; private static class ClassDescriptor extends ClassVisitor { private final SetannotationNames = new LinkedHashSet<>(); private boolean mainMethodFound; ClassDescriptor() { super(SpringAsmInfo.ASM_VERSION); } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { this.annotationNames.add(Type.getType(desc).getClassName()); return null; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { //如果访问方式是public static 且 方法名为 main 且 返回值为 void,则认定该类含有main方法 if (isAccess(access, Opcodes.ACC_PUBLIC, Opcodes.ACC_STATIC) && MAIN_METHOD_NAME.equals(name) && MAIN_METHOD_TYPE.getDescriptor().equals(desc)) { this.mainMethodFound = true; } return null; } private boolean isAccess(int access, int... requiredOpsCodes) { for (int requiredOpsCode : requiredOpsCodes) { if ((access & requiredOpsCode) == 0) { return false; } } return true; } boolean isMainMethodFound() { return this.mainMethodFound; } Set getAnnotationNames() { return this.annotationNames; } } //...
到此这篇关于SpringBoot为啥不用配置启动类的实现的文章就介绍到这了,更多相关SpringBoot 启动类内容请搜索创新互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持创新互联!