【杂谈】SpringBoot为啥不用配置启动类
前言
在学习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;
} }
//...
【杂谈】SpringBoot为啥不用配置启动类的更多相关文章
- SpringBoot无法书写主启动类的情况之一
首先需要引入 spring-boot-starter-web 依赖[springboot web 项目 启动器 jar包]: 如果使用镜像请确保镜像路径正确,可参看笔者博客园m-yb的maven 安装 ...
- 学会springboot多环境配置方案不用5分钟
一 前言 本篇文章的主题是在springboot中写多个配置文件,指定让个配置文件生效,以便于达到在开发环境,测试环境,线上环境根据不同的配置灵活应用:读完本篇你将获得,学会springboot的多环 ...
- SpringBoot swagger-ui.html 配置类继承 WebMvcConfigurationSupport 类后 请求404
1 .SpringBoot启动类加上 注解 @EnableWebMvc @SpringBootApplication@EnableWebMvc public class Application { ...
- SpringBoot系列三:SpringBoot基本概念(统一父 pom 管理、SpringBoot 代码测试、启动注解分析、配置访问路径、使用内置对象、项目打包发布)
声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.了解SpringBoot的基本概念 2.具体内容 在之前所建立的 SpringBoot 项目只是根据官方文档实现的一个基础程 ...
- springboot 启动类启动跳转到前端网页404问题的两个解决方案
前段时间研究springboot 发现使用Application类启动的话, 可以进入Controller方法并且返回数据,但是不能跳转到WEB-INF目录下网页, 前置配置 server: port ...
- springboot系列(三) 启动类中关键注解作用解析
一.Springboot:请求入口 @SpringBootApplication @EnableAspectJAutoProxy @EnableScheduling @EnableTransactio ...
- 关于SpringBoot的自动配置和启动过程
一.简介 Spring Boot简化了Spring应用的开发,采用约定大于配置的思想,去繁从简,很方便就能构建一个独立的.产品级别的应用. 1.传统J2EE开发的缺点 开发笨重.配置繁多复杂.开发效率 ...
- SpringBoot--springboot启动类和controller的配置
作为一个springboot初学者,在探索过程中难免遇到一些坑,边看书边动手,发现书本中的版本是1.0,而我使用的是最新版2.0,所以有些东西不能完全按照书本进行操作,因为2.0中已经不支持1.0中的 ...
- springBoot高级:自动配置分析,事件监听,启动流程分析,监控,部署
知识点梳理 课堂讲义 02-SpringBoot自动配置-@Conditional使用 Condition是Spring4.0后引入的条件化配置接口,通过实现Condition接口可以完成有条件的加载 ...
随机推荐
- Eureka在有虚拟网卡的情况下获取正确的IP
发现问题 最近项目在Eureka注册时,发现一个问题:注册的IP地址不是 192.168.0.XXX 的网络IP,而是另外一个网段的地址,如图 通过 ipconfig 命令查看本机的IP地址发现,该I ...
- django数据库分库migrate
最近在研究微服务和分布式,设计到了数据库分库,记录一下 首先,创建多个数据库,如果是已经生成的数据库,可以分库,这里我是新创建的项目,刚好可以用来尝试 我是用docker创建的mysql数据库容器 拉 ...
- Ctrl+F5和F5区别
F5刷新的内容是从本地缓存中读取刷新,刷新本地缓存 Ctrl+F5直接读取服务器上的最新的内容—— Ctrl+F5会把Internet 临时文件夹的文件删除再重新从服务器下载,也就是彻底刷新页面了.. ...
- css3特性简要概括
---恢复内容开始--- css3新增核心知识 背景和边框 文本效果 2d/3d转换 过渡和动画 多列布局 弹性盒模型 媒体查询 增强选择器 css3浏览器兼容性 css3在线工具 css3gener ...
- Python - 函数形参之必填参数、缺省参数、可变参数、关键字参数的详细使用
Python函数形参 必传参数:平时最常用的,必传确定数量的参数 缺省参数:在调用函数时可以传也可以不传,如果不传将使用默认值 可变参数:可变长度参数 关键字参数:长度可变,但是需要以kv对形式传参 ...
- vue 阻止冒泡 @click.stop=
vue 阻止冒泡 @click.stop= vue中处理冒泡标准姿势 事件修饰符 Vue.js 为 v-on 提供了事件修饰符,修饰符是由点开头的指令后缀来表示的.这些事件修饰符主要有以下几个: st ...
- Java对接百度智能云人脸识别
------------------------->这篇文章就是自己做个笔记<------------------------- 首先登录or注册自己的百度智能云管理中心:https:// ...
- JVM入门必看——JVM结构
转载自:http://blog.csdn.net/yfqnihao 这一节,主要来学习jvm的基本结构,也就是概述.说是概述,内容很多,而且概念量也很大,不过关于概念方面,你不用担心,我完全有信心,让 ...
- 给 ABP vNext 应用安装私信模块
在上一节五分钟完成 ABP vNext 通讯录 App 开发 中,我们用完成了通讯录 App 的基础开发. 这本章节,我们会给通讯录 App 安装私信模块,使不同用户能够通过相互发送消息,并接收新私信 ...
- Java并发编程之CAS第一篇-什么是CAS
Java并发编程之CAS第一篇-什么是CAS 通过前面几篇的学习,我们对并发编程两个高频知识点了解了其中的一个—volatitl.从这一篇文章开始,我们将要学习另一个知识点—CAS.本篇是<凯哥 ...