绍兴1010<兼职网>:【『杂谈』】SpringBoot为啥不用设 置启动[类

admin 7个月前 (04-08) 科技 65 0

前言

〖<在>学习〗SparkJava、Vert.x“等轻量级”Web框架「的」「时」刻,都遇到过打“(〖(“包”)〗)”〖问题〗,【这两个框架打“(〖(“包”)〗)”】「的」「时」刻(都需要添加)分外「的」Maven设〖置〗,并{指定启动}类才气获得可 『执 行[』[「的」JAR“(〖(“包”)〗)”;

‘而’springboot(项目),似乎都不需要分外「的」设〖置〗,直接package《就可以》获得可 『执 行[』[「的」JAR“(〖(“包”)〗)”,这是怎么回事呢?

Vert.x 要怎么配[?

【我们先来看看】,Vert.x打“(〖(“包”)〗)”做哪些设〖置〗

1)‘引入’maven-shade-plugin(插件)

2)<在>(插件)中指定<在>package「完成「时」「触发」」shade操作

3){指定启动}类

<plugin>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <!--<在>mvn package「完成「时」「触发」」-->
            <phase>package</phase>
            <!-- 『执 行[』[shade操作-->
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <transformers>
                    <transformer
                         implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                        <manifestEntries>
                            <!--{指定启动}类-->
                            <main-class>com.test.Starter</main-class>
                        </manifestEntries>
                    </transformer>
                </transformers>
                <artifactSet/>
            </configuration>
        </execution>
    </executions>
</plugin>

效果:

『执 行[』[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 <code>layout=NONE</code> 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());
    Set<Artifact> artifacts = 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 Set<String> annotationNames = 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<String> getAnnotationNames() { return this.annotationNames; } }
//...

 

,

Sunbet

Sunbet www.361223.com Sunbet『是进入』Sunbet(www.sunbet.in)「的」主力站点。Sunbet开放Sunbet《会员开户网址》、Sunbet「代理开户」、Sunbet(手机版下)载、Sunbet『电脑客户端』下载等业务。

Sunbet声明:该文看法仅代表作者自己,与本平台无关。转载请注明:绍兴1010<兼职网>:【『杂谈』】SpringBoot为啥不用设 置启动[类

网友评论

  • (*)

最新评论

标签列表

    文章归档

      站点信息

      • 文章总数:465
      • 页面总数:0
      • 分类总数:8
      • 标签总数:804
      • 评论总数:0
      • 浏览总数:13467