SpringBoot为啥不用配置启动类

简介:

SpringBoot为啥不用配置启动类

前言
在学习SparkJava、Vert.x等轻量级Web框架的时候,都遇到过打包问题,这两个框架打包的时候都需要添加额外的Maven配置,并指定启动类才能得到可执行的JAR包;

而springboot项目,似乎都不需要额外的配置,直接package就可以得到可执行的JAR包,这是怎么回事呢?

Vert.x要怎么配?
我们先来看看,Vert.x打包做哪些配置

1)引入maven-shade-plugin插件

2)在插件中指定在package完成时触发shade操作

3)指定启动类

<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>

效果:

执行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());
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;
}

}
//...

原文地址https://www.cnblogs.com/longfurcat/p/12643878.html

相关文章
|
7月前
|
Java Spring
Spring Boot配置的优先级?
在Spring Boot项目中,配置可通过配置文件和外部配置实现。支持的配置文件包括application.properties、application.yml和application.yaml,优先级依次降低。外部配置常用方式有Java系统属性(如-Dserver.port=9001)和命令行参数(如--server.port=10010),其中命令行参数优先级高于系统属性。整体优先级顺序为:命令行参数 &gt; Java系统属性 &gt; application.properties &gt; application.yml &gt; application.yaml。
1138 0
|
4月前
|
JavaScript Java Maven
【SpringBoot(二)】带你认识Yaml配置文件类型、SpringMVC的资源访问路径 和 静态资源配置的原理!
SpringBoot专栏第二章,从本章开始正式进入SpringBoot的WEB阶段开发,本章先带你认识yaml配置文件和资源的路径配置原理,以方便在后面的文章中打下基础
453 3
|
5月前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
841 5
|
11月前
|
缓存 Java API
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
本文介绍了在Spring Boot中配置Swagger2的方法。通过创建一个配置类,添加`@Configuration`和`@EnableSwagger2`注解,使用Docket对象定义API文档的详细信息,包括标题、描述、版本和包路径等。配置完成后,访问`localhost:8080/swagger-ui.html`即可查看接口文档。文中还提示了可能因浏览器缓存导致的问题及解决方法。
1180 0
微服务——SpringBoot使用归纳——Spring Boot集成 Swagger2 展现在线接口文档——Swagger2 的配置
|
5月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
283 0
探索Spring Boot的@Conditional注解的上下文配置
|
11月前
|
Java 关系型数据库 数据库
微服务——SpringBoot使用归纳——Spring Boot事务配置管理——Spring Boot 事务配置
本文介绍了 Spring Boot 中的事务配置与使用方法。首先需要导入 MySQL 依赖,Spring Boot 会自动注入 `DataSourceTransactionManager`,无需额外配置即可通过 `@Transactional` 注解实现事务管理。接着通过创建一个用户插入功能的示例,展示了如何在 Service 层手动抛出异常以测试事务回滚机制。测试结果表明,数据库中未新增记录,证明事务已成功回滚。此过程简单高效,适合日常开发需求。
1447 0
|
11月前
|
Java 测试技术 微服务
微服务——SpringBoot使用归纳——Spring Boot中的项目属性配置——少量配置信息的情形
本课主要讲解Spring Boot项目中的属性配置方法。在实际开发中,测试与生产环境的配置往往不同,因此不应将配置信息硬编码在代码中,而应使用配置文件管理,如`application.yml`。例如,在微服务架构下,可通过配置文件设置调用其他服务的地址(如订单服务端口8002),并利用`@Value`注解在代码中读取这些配置值。这种方式使项目更灵活,便于后续修改和维护。
208 0
|
11月前
|
SQL Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot使用slf4j进行日志记录—— application.yml 中对日志的配置
在 Spring Boot 项目中,`application.yml` 文件用于配置日志。通过 `logging.config` 指定日志配置文件(如 `logback.xml`),实现日志详细设置。`logging.level` 可定义包的日志输出级别,例如将 `com.itcodai.course03.dao` 包设为 `trace` 级别,便于开发时查看 SQL 操作。日志级别从高到低为 ERROR、WARN、INFO、DEBUG,生产环境建议调整为较高级别以减少日志量。本课程采用 yml 格式,因其层次清晰,但需注意格式要求。
1056 0
|
6月前
|
安全 算法 Java
在Spring Boot中应用Jasypt以加密配置信息。
通过以上步骤,可以在Spring Boot应用中有效地利用Jasypt对配置信息进行加密,这样即使配置文件被泄露,其中的敏感信息也不会直接暴露给攻击者。这是一种在不牺牲操作复杂度的情况下提升应用安全性的简便方法。
1223 10
|
7月前
|
人工智能 安全 Java
Spring Boot yml 配置敏感信息加密
本文介绍了如何在 Spring Boot 项目中使用 Jasypt 实现配置文件加密,包含添加依赖、配置密钥、生成加密值、在配置中使用加密值及验证步骤,并提供了注意事项,确保敏感信息的安全管理。
1370 1

热门文章

最新文章