JAVA为何不用new而用注解_SpringBoot为啥不用配置启动类的实现

前言

在学习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

implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">

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());

Set 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 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 getAnnotationNames() {

return this.annotationNames;

}

}

//...

到此这篇关于SpringBoot为啥不用配置启动类的实现的文章就介绍到这了,更多相关SpringBoot 启动类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringBoot实现定时任务可以使用 Quartz 框架。Quartz 是一个开源的作业调度框架,可以用来创建简单或复杂的作业调度程序。 下面是使用 Quartz 实现定时任务的步骤: 1. 添加 Quartz 的依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.quartz-scheduler</groupId> <artifactId>quartz</artifactId> <version>2.3.0</version> </dependency> ``` 2. 创建 Job 创建一个实现 org.quartz.Job 接口的 Job 。Job 接口只有一个方法 execute(JobExecutionContext context),该方法会在作业执行时被调用。 ```java public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 作业要执行的任务 } } ``` 3. 创建 Trigger Trigger 是定义作业调度时间的组件。可以创建多个 Trigger 对象,每个对象对应一个时间表达式。 ```java Trigger trigger = TriggerBuilder.newTrigger() .withIdentity("triggerName", "groupName") .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) .build(); ``` 上面的代码创建了一个 Trigger 对象,它的名称是 triggerName,所属的组是 groupName。它使用了一个 Cron 表达式,表示每隔 5 秒执行一次作业。 4. 创建 Scheduler Scheduler 是 Quartz 的核心组件,用于管理和调度作业和触发器。创建一个 Scheduler 对象,然后将 Job 和 Trigger 注册到 Scheduler 中。 ```java SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); JobDetail jobDetail = JobBuilder.newJob(MyJob.class) .withIdentity("jobName", "groupName") .build(); scheduler.scheduleJob(jobDetail, trigger); scheduler.start(); ``` 上面的代码创建了一个 Scheduler 对象,并使用 JobBuilder 和 TriggerBuilder 创建了一个 JobDetail 对象和一个 Trigger 对象。然后将 JobDetail 和 Trigger 注册到 Scheduler 中,并启动 Scheduler。 完整的代码示例: ```java public class MyJob implements Job { @Override public void execute(JobExecutionContext context) throws JobExecutionException { // 作业要执行的任务 } } public class QuartzConfig { @Bean public JobDetail jobDetail() { return JobBuilder.newJob(MyJob.class) .withIdentity("jobName", "groupName") .build(); } @Bean public Trigger trigger() { return TriggerBuilder.newTrigger() .withIdentity("triggerName", "groupName") .withSchedule(CronScheduleBuilder.cronSchedule("0/5 * * * * ?")) .build(); } @Bean public Scheduler scheduler() throws SchedulerException { SchedulerFactory schedulerFactory = new StdSchedulerFactory(); Scheduler scheduler = schedulerFactory.getScheduler(); scheduler.scheduleJob(jobDetail(), trigger()); scheduler.start(); return scheduler; } } ``` 在上面的代码中,我们使用了 Spring 的注解 @Bean 来注册 JobDetail、Trigger 和 Scheduler。注意要捕获 SchedulerException 异常。 这样就完成了通过集成 Quartz 来实现 SpringBoot 定时任务的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值