[笔记]spring boot打包jar和war

时间:2022-05-31 09:39:59
  1. 打包jar
    Spring官网Guides下任意一个例子,比如最简单的Building a RESTful Web Service

  2. 打包war
    参考Spring Boot文档 Traditional deployment 85.1 Create a deployable war file
    或例程 spring-boot-sample-war

    按例程看,如果@SpringBootApplication的class直接继承了SpringBootServletInitializer,不用重写config方法也是可以的(builder.main(getClass())、get的就是应用class)。

  3. 打包一个又能发布于tomcat又能java -jar直接跑的war
    2的参考文档里有:

    If you’re using the Spring Boot build tools, marking the embedded servlet container dependency as provided will produce an executable war file with the provided dependencies packaged in a lib-provided directory.

    另外:
    Maven 66.2 Packaging executable jar and war files
    Gradle 67.3 Packaging executable jar and war files

    观察几种配置的发布包子目录和其下jar包,并比较MENIFEST.MF:
    bootRun时有:

    Start-Class: hello.Application
    Spring-Boot-Classes: BOOT-INF/classes/
    Spring-Boot-Lib: BOOT-INF/lib/
    Main-Class: org.springframework.boot.loader.JarLauncher

    不过关心的是war包:

    Start-Class: hello.Application
    Spring-Boot-Classes: WEB-INF/classes/
    Spring-Boot-Lib: WEB-INF/lib/
    Main-Class: org.springframework.boot.loader.WarLauncher

    应该是丢给tomcat时、tomcat只检查servlet定义的WEB-INF/lib路径,但java -jar时、Spring的WarLauncher还引入了存放着tomcat相关jar的lib-provided目录:

    @Override
    public boolean isNestedArchive(Archive.Entry entry) {
    if (entry.isDirectory()) {
    return entry.getName().equals(WEB_INF_CLASSES);
    }
    else {
    return entry.getName().startsWith(WEB_INF_LIB)
    || entry.getName().startsWith(WEB_INF_LIB_PROVIDED);
    }
    }

    所以两种都能跑。