返回总目录页

maven的使用

Maven安装

Linux安装

1、下载maven的yum源
#>wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo

2、安装maven
#>yum install -y maven

3、查看maven版本信息
#>mvn -version

直接yum安装,base镜像里面的版本

 使用Maven的源,然后安装,看看版本是不是更新,看了下没啥变化,没查出新的仓库里面有Maven,这里就先忽略了

[root@mcw12 demo1]# mvn --version
Apache Maven 3.0.5 (Red Hat 3.0.5-17)
Maven home: /usr/share/maven
Java version: 1.8.0_412, vendor: Red Hat, Inc.
Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.412.b08-1.el7_9.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-693.el7.x86_64", arch: "amd64", family: "unix"
[root@mcw12 demo1]# 

 

升级maven

https://apache.osuosl.org/maven/maven-3/3.8.8/binaries/

 

# 更新Java(以Oracle JDK 1.8为例)
sudo apt-get install openjdk-8-jdk  # 以Ubuntu为例
 
# 设置JAVA_HOME环境变量
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
 
# 更新Maven
wget https://apache.osuosl.org/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz
tar -xvf apache-maven-3.6.3-bin.tar.gz
 
# 设置M2_HOME环境变量
export M2_HOME=/path/to/apache-maven-3.6.3
 
# 更新PATH环境变量
export PATH=$PATH:$JAVA_HOME/bin:$M2_HOME/bin

 

[root@mcw12 opt]# mvn --version
Apache Maven 3.8.8 (4c87b05d9aedce574290d1acc98575ed5eb6cd39)
Maven home: /opt/apache-maven-3.8.8
Java version: 1.8.0_412, vendor: Red Hat, Inc., runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.412.b08-1.el7_9.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-693.el7.x86_64", arch: "amd64", family: "unix"
[root@mcw12 opt]# 

安装java17 

 

首先,我们需要确认当前系统是否已经安装了 Java。可以通过运行以下命令来检查:

  1. java -version

如果系统已经安装了 Java,将显示 Java 的版本信息。如果没有安装,我们需要先安装 Java。
要安装 Java 17,我们需要从 Oracle 的官方网站下载适合 CentOS 7/RHEL 7 的 JDK 17 二进制文件。可以使用 wget 命令下载,例如:

  1. wget https://download.oracle.com/java/17/latest/jdk-17_linux-x64_bin.rpm

下载完成后,我们需要使用 rpm 命令安装下载的 JDK 17 二进制文件:

  1. rpm -ivh jdk-17_linux-x64_bin.rpm

安装完成后,我们可以再次运行 java -version 命令来检查是否成功安装了 Java 17。
注意:在安装过程中可能会遇到一些依赖问题,需要手动解决这些依赖问题。例如,如果系统缺少 libaio 或 libaio1,可以使用以下命令进行安装:

  1. sudo yum install libaio libaio-devel

另外,还需要注意系统架构是否与 JDK 17 二进制文件匹配。例如,如果系统是 x86 架构,需要下载 x86 架构的 JDK 17 二进制文件。
安装完成后,可以通过运行以下命令来验证 Java 是否正确安装:

  1. jaclin -version
  2. java -version

以上就是在 CentOS 7/RHEL 7 上安装 Java 17 (OpenJDK 17) 的基本步骤。需要注意的是,在生产环境中,应该根据实际需求选择合适的 Java 版本,并进行合理的配置和管理。

操作之前

[root@mcw12 ~]# java -version
openjdk version "1.8.0_412"
OpenJDK Runtime Environment (build 1.8.0_412-b08)
OpenJDK 64-Bit Server VM (build 25.412-b08, mixed mode)
[root@mcw12 ~]# 

 

操作之后
[root@mcw12 ~]# jaclin -version
-bash: jaclin: command not found
[root@mcw12 ~]# java -version
java version "17.0.11" 2024-04-16 LTS
Java(TM) SE Runtime Environment (build 17.0.11+7-LTS-207)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.11+7-LTS-207, mixed mode, sharing)
[root@mcw12 ~]# 

 

常用maven使用

 

mvn clean 会把原来target目录给删掉重新生成。
mvn install 安装当前工程的输出文件到本地仓库,然后打包
mvn clean install 先删除target文件夹 ,然后打包到target 

1、Maven打包跳过测试的命令

  在使用mvn package进行编译、打包时,Maven会执行src/test/java中的JUnit测试用例,有时为了跳过测试,会使用参数-DskipTests和-Dmaven.test.skip=true,这两个参数的主要区别是:

 -DskipTests,不执行测试用例,但编译测试用例类生成相应的class文件至target/test-classes下。

 -Dmaven.test.skip=true,不执行测试用例,也不编译测试用例类。

类似的 跳过doc生成

  -Dmaven.javadoc.skip=true

 

2、打包时注意:

  2.1)当mvn仓库里缺少jar包,同时又从中央仓库自动下载不下来的时候,就需要自己下载jar包然后放仓库里了,

但是有时候只是简单的把jar和source放仓库的文件夹下,并不管用,这个时候你可以用命令把jar把打进去:

mvn install:install-file -Dfile=D:\xxx.jar  -DgroupId=commons-dbcp -DartifactId= commons-dbcp -Dversion= 1.4 -Dpackaging=jar

-Dfile 是存在本地磁盘里jar 的路径,后面的就不用说了吧!install:install-file   看清楚了!!!这个-file跟install是连着的。

 

  2.2)mvn dependency:tree命令解决jar包冲突
当项目出现jar包冲突时,用命令mvn dependency:tree 查看依赖情况
mvn dependency:tree 查看依赖树,查看包结构间的依赖
mvn dependency:tree >d:/tmp 把结果输出到文件,
然后再pom.xml文件里排除掉冲突的jar包


<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-servlet</artifactId>
<version>${tiles.version}</version>
<exclusions>
<exclusion>
<groupId> org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency> 

解决依赖关系,根据POM文件,下载或者更新该项目所依赖的库文件:

mvn dependency:resolve-plugins

 

centos上Maven的使用演示

准备代码

我这里直接将代码整体复制到Linux服务器上。一般情况是git从gitlab上拉取代码

将java源码用maven打包并用java -jar启动的的研究过程 

将代码已经上传上去了

 

执行命令失败maven版本不同

 

 

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:3.3.2:clean (default-clean) on project demo1: The plugin org.apache.maven.plugins:maven-clean-plugin:3.3.2 requires Maven version 3.2.5 -> [Help 1]

 执行命令时自动下载的版本是3.3.2

而我的maven版本是3.0.5。我升级下自己的maven,Maven version应该要大于 3.2.5

 升级之后查看。升级方法见上面章节

[root@mcw12 opt]# mvn --version
Apache Maven 3.8.8 (4c87b05d9aedce574290d1acc98575ed5eb6cd39)
Maven home: /opt/apache-maven-3.8.8
Java version: 1.8.0_412, vendor: Red Hat, Inc., runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.412.b08-1.el7_9.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-693.el7.x86_64", arch: "amd64", family: "unix"
[root@mcw12 opt]# 

再次执行

可以看到已经成功删除target目录

[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src  target
[root@mcw12 demo1]# mvn clean
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.3.2:clean (default-clean) @ demo1 ---
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/4.0.0/plexus-utils-4.0.0.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/4.0.0/plexus-utils-4.0.0.pom (8.7 kB at 7.1 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus/13/plexus-13.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus/13/plexus-13.pom (27 kB at 128 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/junit/junit-bom/5.9.3/junit-bom-5.9.3.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/junit/junit-bom/5.9.3/junit-bom-5.9.3.pom (5.6 kB at 37 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/4.0.0/plexus-utils-4.0.0.jar
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/4.0.0/plexus-utils-4.0.0.jar (192 kB at 531 kB/s)
[INFO] Deleting /root/demo1/target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.107 s
[INFO] Finished at: 2024-07-07T21:39:04+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src
[root@mcw12 demo1]# 

重新打包,报错

[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src
[root@mcw12 demo1]# mvn pacage
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.568 s
[INFO] Finished at: 2024-07-07T21:40:34+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Unknown lifecycle phase "pacage". You must specify a valid lifecycle phase or a goal in the format <plugin-prefix>:<goal> or <plugin-group-id>:<plugin-artifact-id>[:<plugin-version>]:<goal>. Available lifecycle phases are: validate, initialize, generate-sources, process-sources, generate-resources, process-resources, compile, process-classes, generate-test-sources, process-test-sources, generate-test-resources, process-test-resources, test-compile, process-test-classes, test, prepare-package, package, pre-integration-test, integration-test, post-integration-test, verify, install, deploy, pre-clean, clean, post-clean, pre-site, site, post-site, site-deploy. -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/LifecyclePhaseNotFoundException
[root@mcw12 demo1]# 

 

 将项目下的这段注释掉,用其它的替代试试

用下面的替代

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.2.0</version>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <mainClass>com.yourcompany.yourapp.MainClass</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <!-- 添加maven-assembly-plugin来创建带有所有依赖的fat JAR -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.3.0</version>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.yourcompany.yourapp.MainClass</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

重新打包之后,报错了

 

Downloaded from central: https://repo.maven.apache.org/maven2/com/thoughtworks/qdox/qdox/2.0.3/qdox-2.0.3.jar (334 kB at 352 kB/s)
[INFO] Recompiling the module because of changed dependency.
[INFO] Compiling 3 source files with javac [debug parameters release 17] to target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] /root/demo1/src/main/java/com/example/demo/Demo1Application.java:[3,32] cannot access org.springframework.boot.SpringApplication
  bad class file: /root/.m2/repository/org/springframework/boot/spring-boot/3.3.1/spring-boot-3.3.1.jar(org/springframework/boot/SpringApplication.class)
    class file has wrong version 61.0, should be 52.0
    Please remove or make sure it appears in the correct subdirectory of the classpath.
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  43.995 s
[INFO] Finished at: 2024-07-07T21:54:24+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile (default-compile) on project demo1: Compilation failure
[ERROR] /root/demo1/src/main/java/com/example/demo/Demo1Application.java:[3,32] cannot access org.springframework.boot.SpringApplication
[ERROR]   bad class file: /root/.m2/repository/org/springframework/boot/spring-boot/3.3.1/spring-boot-3.3.1.jar(org/springframework/boot/SpringApplication.class)
[ERROR]     class file has wrong version 61.0, should be 52.0
[ERROR]     Please remove or make sure it appears in the correct subdirectory of the classpath.
[ERROR] 
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src  target
[root@mcw12 demo1]# ls target/
classes  generated-sources  maven-status
[root@mcw12 demo1]#

好像是版本高了

我们Linux服务器是jdk8,而这个项目使用java 17 进行构建和运行的。

 根据上面章节,将jdk升级

[root@mcw12 ~]# java -version
java version "17.0.11" 2024-04-16 LTS
Java(TM) SE Runtime Environment (build 17.0.11+7-LTS-207)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.11+7-LTS-207, mixed mode, sharing)
[root@mcw12 ~]# 

删除之前的打包,重新打包一下,成功打成jar包

[root@mcw12 ~]# cd /root/demo1/
[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src  target
[root@mcw12 demo1]# mvn clean
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.3.2:clean (default-clean) @ demo1 ---
[INFO] Deleting /root/demo1/target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.871 s
[INFO] Finished at: 2024-07-07T22:15:59+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src
[root@mcw12 demo1]# mvn package
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:3.3.1:resources (default-resources) @ demo1 ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] 
[INFO] --- maven-compiler-plugin:3.13.0:compile (default-compile) @ demo1 ---
[INFO] Recompiling the module because of changed source code.
[INFO] Compiling 3 source files with javac [debug parameters release 17] to target/classes
[INFO] 
[INFO] --- maven-resources-plugin:3.3.1:testResources (default-testResources) @ demo1 ---
[INFO] skip non existing resourceDirectory /root/demo1/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.13.0:testCompile (default-testCompile) @ demo1 ---
[INFO] Recompiling the module because of changed dependency.
[INFO] Compiling 1 source file with javac [debug parameters release 17] to target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:3.2.5:test (default-test) @ demo1 ---
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/maven-surefire-common/3.2.5/maven-surefire-common-3.2.5.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/maven-surefire-common/3.2.5/maven-surefire-common-3.2.5.pom (6.2 kB at 6.9 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-api/3.2.5/surefire-api-3.2.5.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-api/3.2.5/surefire-api-3.2.5.pom (3.5 kB at 24 kB/s)
..........
Downloading from central: https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-launcher/1.10.2/junit-platform-launcher-1.10.2.jar
Downloaded from central: https://repo.maven.apache.org/maven2/org/junit/platform/junit-platform-launcher/1.10.2/junit-platform-launcher-1.10.2.jar (184 kB at 973 kB/s)
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.demo.Demo1ApplicationTests
22:16:39.183 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.demo.Demo1ApplicationTests]: Demo1ApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
22:16:39.373 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration com.example.demo.Demo1Application for test class com.example.demo.Demo1ApplicationTests

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.1)

2024-07-07T22:16:40.213+08:00  INFO 4677 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Starting Demo1ApplicationTests using Java 17.0.11 with PID 4677 (started by root in /root/demo1)
2024-07-07T22:16:40.215+08:00  INFO 4677 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : No active profile set, falling back to 1 default profile: "default"
2024-07-07T22:16:43.130+08:00  INFO 4677 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Started Demo1ApplicationTests in 3.431 seconds (process running for 6.013)
Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.770 s -- in com.example.demo.Demo1ApplicationTests
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] 
[INFO] --- maven-war-plugin:3.4.0:war (default-war) @ demo1 ---
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/maven-archiver/3.6.0/maven-archiver-3.6.0.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/maven-archiver/3.6.0/maven-archiver-3.6.0.pom (3.9 kB at 27 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/shared/maven-shared-components/36/maven-shared-components-36.pom
............
Downloaded from central: https://repo.maven.apache.org/maven2/org/sonatype/sisu/sisu-guice/2.1.7/sisu-guice-2.1.7-noaop.jar (472 kB at 89 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/com/github/luben/zstd-jni/1.5.5-2/zstd-jni-1.5.5-2.jar (5.9 MB at 364 kB/s)
[INFO] Packaging webapp
[INFO] Assembling webapp [demo1] in [/root/demo1/target/demo1-0.0.1-SNAPSHOT]
[INFO] Processing war project
[INFO] Building war: /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
[INFO] 
[INFO] --- maven-assembly-plugin:3.3.0:single (default) @ demo1 ---
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/2.0.4/plexus-utils-2.0.4.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-utils/2.0.4/plexus-utils-2.0.4.pom (3.3 kB at 27 kB/s)
Downloading from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-component-annotations/2.0.0/plexus-component-annotations-2.0.0.pom
..........
Downloaded from central: https://repo.maven.apache.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.13.2.2/jackson-databind-2.13.2.2.jar (1.5 MB at 198 kB/s)
[INFO] Building jar: /root/demo1/target/demo1-0.0.1-SNAPSHOT-jar-with-dependencies.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  03:22 min
[INFO] Finished at: 2024-07-07T22:19:39+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src  target
[root@mcw12 demo1]# ls target/
archive-tmp  demo1-0.0.1-SNAPSHOT                            demo1-0.0.1-SNAPSHOT.war  generated-test-sources  maven-status      test-classes
classes      demo1-0.0.1-SNAPSHOT-jar-with-dependencies.jar  generated-sources         maven-archiver          surefire-reports
[root@mcw12 demo1]# 

启动jar包失败了

[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src  target
[root@mcw12 demo1]# ls target/
archive-tmp  demo1-0.0.1-SNAPSHOT                            demo1-0.0.1-SNAPSHOT.war  generated-test-sources  maven-status      test-classes
classes      demo1-0.0.1-SNAPSHOT-jar-with-dependencies.jar  generated-sources         maven-archiver          surefire-reports
[root@mcw12 demo1]# ls /root/demo1/target/demo1-0.0.1-SNAPSHOT.war 
/root/demo1/target/demo1-0.0.1-SNAPSHOT.war
[root@mcw12 demo1]# java -jar /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
no main manifest attribute, in /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
[root@mcw12 demo1]# java -jar /root/demo1/target/demo1-0.0.1-SNAPSHOT-jar-with-dependencies.jar 
Error: Could not find or load main class com.yourcompany.yourapp.MainClass
Caused by: java.lang.ClassNotFoundException: com.yourcompany.yourapp.MainClass
[root@mcw12 demo1]# 

 

 

把主类改成下面这个试试

 修改之后如下:

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.2.0</version>
        <configuration>
          <archive>
            <manifest>
              <addClasspath>true</addClasspath>
              <mainClass>com.example.demo.HelloController</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <!-- 添加maven-assembly-plugin来创建带有所有依赖的fat JAR -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.3.0</version>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.example.demo.HelloController</mainClass>
            </manifest>
          </archive>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

然后重新打包,貌似之前下载包的动作已经没了,估计是本地缓存了

[root@mcw12 demo1]# ls
HELP.md mvnw mvnw.cmd pom.xml src target
[root@mcw12 demo1]# mvn clean
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO] from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- maven-clean-plugin:3.3.2:clean (default-clean) @ demo1 ---
[INFO] Deleting /root/demo1/target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.861 s
[INFO] Finished at: 2024-07-08T02:36:10+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]# ls
HELP.md mvnw mvnw.cmd pom.xml src
[root@mcw12 demo1]# mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO] from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.3.1:resources (default-resources) @ demo1 ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO]
[INFO] --- maven-compiler-plugin:3.13.0:compile (default-compile) @ demo1 ---
[INFO] Recompiling the module because of changed source code.
[INFO] Compiling 3 source files with javac [debug parameters release 17] to target/classes
[INFO]
[INFO] --- maven-resources-plugin:3.3.1:testResources (default-testResources) @ demo1 ---
[INFO] skip non existing resourceDirectory /root/demo1/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.13.0:testCompile (default-testCompile) @ demo1 ---
[INFO] Recompiling the module because of changed dependency.
[INFO] Compiling 1 source file with javac [debug parameters release 17] to target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:3.2.5:test (default-test) @ demo1 ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.demo.Demo1ApplicationTests
02:37:20.926 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.demo.Demo1ApplicationTests]: Demo1ApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
02:37:21.068 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration com.example.demo.Demo1Application for test class com.example.demo.Demo1ApplicationTests

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/

:: Spring Boot :: (v3.3.1)

2024-07-08T02:37:21.844+08:00 INFO 19653 --- [demo1] [ main] com.example.demo.Demo1ApplicationTests : Starting Demo1ApplicationTests using Java 17.0.11 with PID 19653 (started by root in /root/demo1)
2024-07-08T02:37:21.860+08:00 INFO 19653 --- [demo1] [ main] com.example.demo.Demo1ApplicationTests : No active profile set, falling back to 1 default profile: "default"
2024-07-08T02:37:24.476+08:00 INFO 19653 --- [demo1] [ main] com.example.demo.Demo1ApplicationTests : Started Demo1ApplicationTests in 3.142 seconds (process running for 4.853)
Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.194 s -- in com.example.demo.Demo1ApplicationTests
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-war-plugin:3.4.0:war (default-war) @ demo1 ---
[INFO] Packaging webapp
[INFO] Assembling webapp [demo1] in [/root/demo1/target/demo1-0.0.1-SNAPSHOT]
[INFO] Processing war project
[INFO] Building war: /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
[INFO]
[INFO] --- maven-assembly-plugin:3.3.0:single (default) @ demo1 ---
[INFO] Building jar: /root/demo1/target/demo1-0.0.1-SNAPSHOT-jar-with-dependencies.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 20.720 s
[INFO] Finished at: 2024-07-08T02:37:36+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]#

 再次执行还是报错

[root@mcw12 demo1]# java -jar  /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
no main manifest attribute, in /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
[root@mcw12 demo1]# 

 

会不是是这个才是主属性呢

 改成带有main的那个类名的路径之后,再次重新打包,打包过程比之前长一点,看测试好像是可以启动一个vm

<mainClass>com.example.demo.Demo1Application</mainClass>

[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src  target
[root@mcw12 demo1]# mvn clean
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.3.2:clean (default-clean) @ demo1 ---
[INFO] Deleting /root/demo1/target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.861 s
[INFO] Finished at: 2024-07-08T02:36:10+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src
[root@mcw12 demo1]# mvn package
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:3.3.1:resources (default-resources) @ demo1 ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] 
[INFO] --- maven-compiler-plugin:3.13.0:compile (default-compile) @ demo1 ---
[INFO] Recompiling the module because of changed source code.
[INFO] Compiling 3 source files with javac [debug parameters release 17] to target/classes
[INFO] 
[INFO] --- maven-resources-plugin:3.3.1:testResources (default-testResources) @ demo1 ---
[INFO] skip non existing resourceDirectory /root/demo1/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.13.0:testCompile (default-testCompile) @ demo1 ---
[INFO] Recompiling the module because of changed dependency.
[INFO] Compiling 1 source file with javac [debug parameters release 17] to target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:3.2.5:test (default-test) @ demo1 ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.demo.Demo1ApplicationTests
02:37:20.926 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.demo.Demo1ApplicationTests]: Demo1ApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
02:37:21.068 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration com.example.demo.Demo1Application for test class com.example.demo.Demo1ApplicationTests

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.1)

2024-07-08T02:37:21.844+08:00  INFO 19653 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Starting Demo1ApplicationTests using Java 17.0.11 with PID 19653 (started by root in /root/demo1)
2024-07-08T02:37:21.860+08:00  INFO 19653 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : No active profile set, falling back to 1 default profile: "default"
2024-07-08T02:37:24.476+08:00  INFO 19653 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Started Demo1ApplicationTests in 3.142 seconds (process running for 4.853)
Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.194 s -- in com.example.demo.Demo1ApplicationTests
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] 
[INFO] --- maven-war-plugin:3.4.0:war (default-war) @ demo1 ---
[INFO] Packaging webapp
[INFO] Assembling webapp [demo1] in [/root/demo1/target/demo1-0.0.1-SNAPSHOT]
[INFO] Processing war project
[INFO] Building war: /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
[INFO] 
[INFO] --- maven-assembly-plugin:3.3.0:single (default) @ demo1 ---
[INFO] Building jar: /root/demo1/target/demo1-0.0.1-SNAPSHOT-jar-with-dependencies.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  20.720 s
[INFO] Finished at: 2024-07-08T02:37:36+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]# 
[root@mcw12 demo1]# java -jar  /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
no main manifest attribute, in /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
[root@mcw12 demo1]# 
[root@mcw12 demo1]# vim pom.xml 
[root@mcw12 demo1]# mvn clean
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.3.2:clean (default-clean) @ demo1 ---
[INFO] Deleting /root/demo1/target
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  0.752 s
[INFO] Finished at: 2024-07-08T02:43:05+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src
[root@mcw12 demo1]# mvn package
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-resources-plugin:3.3.1:resources (default-resources) @ demo1 ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] 
[INFO] --- maven-compiler-plugin:3.13.0:compile (default-compile) @ demo1 ---
[INFO] Recompiling the module because of changed source code.
[INFO] Compiling 3 source files with javac [debug parameters release 17] to target/classes
[INFO] 
[INFO] --- maven-resources-plugin:3.3.1:testResources (default-testResources) @ demo1 ---
[INFO] skip non existing resourceDirectory /root/demo1/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.13.0:testCompile (default-testCompile) @ demo1 ---
[INFO] Recompiling the module because of changed dependency.
[INFO] Compiling 1 source file with javac [debug parameters release 17] to target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:3.2.5:test (default-test) @ demo1 ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.demo.Demo1ApplicationTests
02:43:17.573 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.demo.Demo1ApplicationTests]: Demo1ApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
02:43:17.784 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration com.example.demo.Demo1Application for test class com.example.demo.Demo1ApplicationTests

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.1)

2024-07-08T02:43:18.531+08:00  INFO 20109 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Starting Demo1ApplicationTests using Java 17.0.11 with PID 20109 (started by root in /root/demo1)
2024-07-08T02:43:18.533+08:00  INFO 20109 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : No active profile set, falling back to 1 default profile: "default"
2024-07-08T02:43:21.119+08:00  INFO 20109 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Started Demo1ApplicationTests in 3.054 seconds (process running for 4.653)
Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 5.305 s -- in com.example.demo.Demo1ApplicationTests
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] 
[INFO] --- maven-war-plugin:3.4.0:war (default-war) @ demo1 ---
[INFO] Packaging webapp
[INFO] Assembling webapp [demo1] in [/root/demo1/target/demo1-0.0.1-SNAPSHOT]
[INFO] Processing war project
[INFO] Building war: /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
[INFO] 
[INFO] --- maven-assembly-plugin:3.3.0:single (default) @ demo1 ---
[INFO] Building jar: /root/demo1/target/demo1-0.0.1-SNAPSHOT-jar-with-dependencies.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  20.808 s
[INFO] Finished at: 2024-07-08T02:43:33+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]# 

结果还是不行

[root@mcw12 demo1]# java -jar /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
no main manifest attribute, in /root/demo1/target/demo1-0.0.1-SNAPSHOT.war
[root@mcw12 demo1]# 

 

把idea上打出的包复制到服务器上是可以的,说明还是我们在Linux上用maven打包有点问题

 

 再次构建执行,这次用mvn打的包

 这次成功了

 

再次往上追溯一下,发现是之前mvn pacage 打包命令写错了,然后我改了下pom.xml文件。实际上不需要修改的。直接mvn package打包就可以了。然后java -jar启动。就可以用这个web服务了。

 

也就是将在源代码根目录下,直接执行mvn clean ,mvn package就可以获得java包了。

 

Linux上用maven创建一个springboot项目??

编辑pom.xml文件

 

就像composer的composer.json、Make的makefile文件一样,Maven项目的核心是pom.xml文件。POM(Project Object Model,项目对象模型)定义了项目的基本信息,用于描述项目如何构建,声明项目依赖,等等。

现在我们不借助任何其它命令和IDE,来创建一个Maven项目。

首先,编写pom.xml文件。,从一个Hello World项目进行演示。以下就是创建项目的POM文件。

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jellythink.HelloWorld</groupId>
  <artifactId>hello-world</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>hello-world</name>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>

对于POM文件,现在细说一下。

  • 代码的第一行是XML头,指定了该xml文档的版本和编码方式。紧接着是project元素,project是所有pom.xml的根元素,它还声明了一些POM相关的命名空间及xsd元素;
  • 根元素下的第一个子元素modelVersion指定了当前POM模型的版本,对于Maven 2和Maven 3来说,它只能是4.0.0;
  • 接下来就是groupIdartifactIdversion了,这三个是上述代码三个元素。这三个元素定义了一个项目的基本坐标,在Maven的世界里,所有的jar和war都是基于坐标进行区分的,会面的文章还会细说坐标;
  • groupId定义了项目属于哪个组,这个组往往和项目所在的组织或公司存在关联,一般是使用组织或公司的域名;比如上面的groupIdcom.jellythink.HelloWorld,其中com.jellythink就是我的网站域名倒过来写的,而HelloWorld则是整个项目的名称;
  • artifactId定义了当前Maven项目在组中唯一的ID,一般一个大项目组下面可能会包含多个子项目或子模块,而这个artifactId就是子项目或者子模块的名称;
  • version指定了这个项目当前的版本,后面的文章还会细说Maven中版本的含义;
  • name元素声明了一个对于用户更为友好的项目名称,方便后期的管理;
  • properties指定了Maven的一些重要属性,后续还会重点说这个属性的一些配置。

创建完pom.xml文件后,接下来就是创建代码文件了。在Maven中,有这样的一个约定,项目主代码都位于src/main/java目录,项目测试代码都位于src/test/java目录;接下来我们先按照这个约定分别创建目录,然后在代码目录创建com/jellythink/HelloWorld/App.java文件;在测试目录创建com/jellythink/HelloWorld/AppTest.java文件。

还是老规矩,我们在App.java中打印Hello World!,代码如下:

public class App {
    public String sayHello() {
        return "Hello World";
    }

    public static void main( String[] args ) {
        System.out.println(new App().sayHello());
    }
}

同理,对于AppTest.java中编写以下单元测试代码:

public class AppTest {
    @Test
    public void testSayHello() {
        App app = new App();
        String result = app.sayHello();
        assertEquals("Hello World", result);
    }
}

在Java中,我们进行单元测试时,基本上都是使用的JUnit,要使用JUnit这个包,我们就需要引入这个依赖包,此时,我们就需要在pom.xml中添加以下依赖内容:

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>

代码中添加了dependencies元素,该元素下可以包含多个dependency元素以声明项目的依赖。前面也说过,groupIdartifactIdversion是任何一个Maven项目最基本的坐标,JUnit也不例外;scope表示依赖范围,后续的文章还会细说这个依赖和测试相关的内容。

编译和测试

万事俱备,只欠东风。接下来我们编译和测试。

搞定代码后,使用Maven进行编译,在项目根目录下运行mvn clean compile命令。执行输出如下图所示:

 

clean告诉Maven清理输出目录target,compile告诉Maven编译项目主代码。从输出中看到Maven首先执行了clean:clean任务,删除target目录。默认情况下,Maven构建的所有输出都在target目录中;接着执行resources:resources任务;最后执行compiler:compile任务,将项目主代码编译至target/classes目录。

上面说到的clean:cleanresources:resourcescompiler:compile都对应了Maven的生命周期及插件,这个在后面还会有专题文章细说。

编译完成后,我们一般都会运行测试代码进行单元测试,虽然很多情况下,我们并没有这么做,但是我还是建议大家通过Maven做一些自动化的单元测试。

测试用例编写完毕之后就可以调用Maven执行测试,运行mvn clean test命令,输出如下:

 

从输出可以看到,Maven依次执行了clean:cleanresources:resourcescompiler:compileresources:testResourcescompiler:testCompilesurefire:test。现阶段,我们需要明白这是Maven的生命周期的一个特性,这个生命周期后续还会细说。

到此,编译和测试均通过了,接着我们进行应用打包和运行。

打包和运行

打包就是将我们编写的应用打成JAR包或者WAR包。在我们的HelloWorld示例程序POM中,并没有指定打包类型,Maven则默认打包成JAR包。我们执行mvn clean package命令就可以完成打包。mvn clean package命令的输出如下:

 

可以看到,Maven在打包之前会执行编译、测试等操作,最后通过jar:jar任务负责打包。实际上就是jar插件的jar目标将项目主代码打包成一个名为hello-world-1.0-SNAPSHOT.jar的文件,这个最终生成的包会保存在target目录下,它是根据artifact-version.jar规则进行命名的;当然了,我们可以使用finalName属性来自定义该文件的名称。

到现在,我们得到了这个JAR包,如果别的项目要引用这个JAR包时,我们将这个JAR包复制到其它项目的classpath中就OK了。但是这样拷贝就违背了我们当初想要自动解决依赖的问题,所以如何才能让其它的Maven项目直接引用这个JAR包呢?我们需要执行mvn clean install命令。

 

从输出可以看到,在打包之后,又执行了安装任务install:install,最后将项目输出的JAR包安装到了Maven本地仓库中,我们可以在本地的仓库文件夹中能看到这个示例项目的pom和jar包。

到目前为止,通过这个示例项目体验了mvn clean compilemvn clean testmvn clean packagemvn clean install。执行test之前会先执行compile的,执行package之前会先执行test的,而类似地,install之前会执行package。我们可以在任何一个Maven项目中执行这些命令。

最后,不要忘了,我们生成的JAR包是有main方法的,也就是说这个JAR包是可以单独运行的;但是,由于带有main方法的类信息没有添加到manifest中,所以默认打包生成的jar是不能够直接运行的(使用jd-gui打开jar文件中的META-INF/MANIFEST.MF文件,将无法看到Main-Class一行)。为了生成可执行jar文件,需要借助Apache Maven Shade Plugin来完成,我们需要在pom.xml文件中以下插件配置:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                            <mainClass>com.jellythink.HelloWorld.App</mainClass>
                        </transformer>
                    </transformers>
                </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

接下来,我们再执行mvn clean install命令,待构建完成之后在target目录下可以看到hello-world-1.0-SNAPSHOT.jar和original-hello-world-1.0-SNAPSHOT.jar,前面的是带有Main-Class信息的可运行jar,后者是原始的jar。我们执行以下命令:

java -jar hello-world-1.0-SNAPSHOT.jar

就可以正常执行。

使用Archetype生成项目骨架

上面非常详细的总结了如何全手动的创建一个Maven工程。通过上面的总结,我们大体可以总结以下几步:

  • 在项目根目录创建pom.xml文件;
  • 创建src/main/java目录,并在该目录开发项目主代码;
  • 创建src/test/java目录,并在该目录开发项目测试代码;

上面的三步我们成为Maven项目的骨架,也就是现在常说的“脚手架”。如果我们每创建一个Maven项目都需要把上面的步骤执行一次,确实很麻烦,那怎么办?程序就是解放人工的,让人来偷懒的。所以,在Maven中,我们可以通过Archetype生成项目骨架,将上面的步骤流程化。比如,现在我们要创建一个Maven项目,我们只需要输入以下命令就OK了。

mvn archetype:generate

执行这个命令后,后看到很多输出,有很多可用的Archetype供我们选择,每一个Archetype前面都会对应有一个编号,我们根据我们的需要,选择我们对应的骨架来创建项目就好了。然后再按照提示,输出新项目的groupId、artifactId、version和包名package,一个Maven项目就创建成功了。

我们在运行mvn archetype:generate时,实际上是在运行maven-archetype-plugin插件。

 

@@@实操过程

[root@mcw12 test]# ls
[root@mcw12 test]# vim pom.xml
[root@mcw12 test]# ls
pom.xml
[root@mcw12 test]# cat pom.xml 
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jellythink.HelloWorld</groupId>
  <artifactId>hello-world</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>hello-world</name>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>
[root@mcw12 test]# mkdir -p src/main/java src/test/java
[root@mcw12 test]# tree 
.
├── pom.xml
└── src
    ├── main
    │   └── java
    └── test
        └── java

5 directories, 1 file
[root@mcw12 test]# mkdir src/main/java/com/jellythink/HelloWorld/
mkdir: cannot create directory ‘src/main/java/com/jellythink/HelloWorld/’: No such file or directory
[root@mcw12 test]# mkdir -p src/main/java/com/jellythink/HelloWorld/ src/test/java/com/jellythink/HelloWorld/
[root@mcw12 test]# vim src/main/java/com/jellythink/HelloWorld/App.java
[root@mcw12 test]# vim src/test/java/com/jellythink/HelloWorld/AppTest.java
[root@mcw12 test]# vim pom.xml 
[root@mcw12 test]# tree
.
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── jellythink
    │               └── HelloWorld
    │                   └── App.java
    └── test
        └── java
            └── com
                └── jellythink
                    └── HelloWorld
                        └── AppTest.java

11 directories, 3 files
[root@mcw12 test]# cat src/main/java/com/jellythink/HelloWorld/App.java
public class App {
    public String sayHello() {
        return "Hello World";
    }

    public static void main( String[] args ) {
        System.out.println(new App().sayHello());
    }
}
[root@mcw12 test]# cat src/test/java/com/jellythink/HelloWorld/AppTest.java
public class AppTest {
    @Test
    public void testSayHello() {
        App app = new App();
        String result = app.sayHello();
        assertEquals("Hello World", result);
    }
}
[root@mcw12 test]# cat pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jellythink.HelloWorld</groupId>
  <artifactId>hello-world</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>hello-world</name>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>
</project>
[root@mcw12 test]# 

开始执行编译报错

[root@mcw12 test]# ls
pom.xml  src
[root@mcw12 test]# tree 
.
├── pom.xml
└── src
    ├── main
    │   └── java
    │       └── com
    │           └── jellythink
    │               └── HelloWorld
    │                   └── App.java
    └── test
        └── java
            └── com
                └── jellythink
                    └── HelloWorld
                        └── AppTest.java

11 directories, 3 files
[root@mcw12 test]# mvn clean compile
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------< com.jellythink.HelloWorld:hello-world >----------------
[INFO] Building hello-world 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
Downloaded from central: https://repo.maven.apache.org/maven2/com/google/collections/google-collections/1.0/google-collections-1.0.jar (640 kB at 757 kB/s)
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /root/mcw/test/target/classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] Source option 5 is no longer supported. Use 7 or later.
[ERROR] Target option 5 is no longer supported. Use 7 or later.
[INFO] 2 errors 
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  17.512 s
[INFO] Finished at: 2024-07-09T08:54:04+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project hello-world: Compilation failure: Compilation failure: 
[ERROR] Source option 5 is no longer supported. Use 7 or later.
[ERROR] Target option 5 is no longer supported. Use 7 or later.
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[root@mcw12 test]# 

这个错误表明 Maven 在编译你的 hello-world 项目时遇到了问题,因为编译器配置中指定的 Java 源码版本(source level)是 5,但是当前环境中已经不再支持这个版本。从错误提示来看,建议使用 Java 7 或更高版本来编译你的项目。

要解决这个问题,你需要更新 Maven 项目中的 pom.xml 文件,以指定一个更高版本的 Java 源码级别。以下是如何修改 pom.xml 文件来设置 Java 编译版本的步骤:

  1. 打开你的 pom.xml 文件。

  2. 找到 <properties> 部分(如果还没有,就添加它)。

  3. 在 <properties> 部分中添加或修改 maven.compiler.source 和 maven.compiler.target 属性,以指定你希望使用的 Java 版本。例如,如果你希望使用 Java 8,你可以添加如下配置:

    <properties>  
        <maven.compiler.source>1.8</maven.compiler.source>  
        <maven.compiler.target>1.8</maven.compiler.target>  
    </properties>
     

    如果你不确定要使用哪个 Java 版本,可以选择 Java 8(1.8)或更高版本,这通常是大多数项目的良好起点。

  4. 确保你的 JDK 安装与你在 pom.xml 中指定的版本相匹配。你可以在命令行中运行 java -version 来检查当前安装的 JDK 版本。

  5. 保存 pom.xml 文件并重新运行 Maven 构建命令(如 mvn clean install)。

  6. 如果问题仍然存在,检查你的 IDE(如 Eclipse, IntelliJ IDEA 等)是否也配置为使用正确的 JDK 版本。在 IDE 的设置中,你可以找到配置 Java 编译器版本的选项。

  7. 如果你的项目依赖于其他模块或库,确保这些依赖也兼容你选择的 Java 版本。

通过上述步骤,你应该能够解决因 Java 源码版本过旧而导致的编译错误。

 

按照上面添加版本之后,编译成功

[root@mcw12 test]# vim pom.xml 
[root@mcw12 test]# java -version
java version "17.0.11" 2024-04-16 LTS
Java(TM) SE Runtime Environment (build 17.0.11+7-LTS-207)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.11+7-LTS-207, mixed mode, sharing)
[root@mcw12 test]# mvn clean compile
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------< com.jellythink.HelloWorld:hello-world >----------------
[INFO] Building hello-world 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ hello-world ---
[INFO] Deleting /root/mcw/test/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ hello-world ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /root/mcw/test/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ hello-world ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /root/mcw/test/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.087 s
[INFO] Finished at: 2024-07-09T09:01:17+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 test]# cat pom.xml 
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jellythink.HelloWorld</groupId>
  <artifactId>hello-world</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>hello-world</name>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>  
    <maven.compiler.target>1.8</maven.compiler.target>  
  </properties>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>
</project>
[root@mcw12 test]# 

查看目录层级

[root@mcw12 test]# ls
pom.xml  src  target
[root@mcw12 test]# tree 
.
├── pom.xml
├── src
│   ├── main
│   │   └── java
│   │       └── com
│   │           └── jellythink
│   │               └── HelloWorld
│   │                   └── App.java
│   └── test
│       └── java
│           └── com
│               └── jellythink
│                   └── HelloWorld
│                       └── AppTest.java
└── target
    ├── classes
    │   └── App.class
    ├── generated-sources
    │   └── annotations
    └── maven-status
        └── maven-compiler-plugin
            └── compile
                └── default-compile
                    ├── createdFiles.lst
                    └── inputFiles.lst

19 directories, 6 files
[root@mcw12 test]# 

打包报错

[root@mcw12 test]# ls 
pom.xml  src  target
[root@mcw12 test]# ls target/
classes  generated-sources  maven-status
[root@mcw12 test]# mvn clean package
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------< com.jellythink.HelloWorld:hello-world >----------------
[INFO] Building hello-world 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
Downloaded from central: https://repo.maven.apache.org/maven2/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar (45 kB at 111 kB/s)
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ hello-world ---
[INFO] Deleting /root/mcw/test/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ hello-world ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /root/mcw/test/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ hello-world ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /root/mcw/test/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ hello-world ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /root/mcw/test/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ hello-world ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /root/mcw/test/target/test-classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] /root/mcw/test/src/test/java/com/jellythink/HelloWorld/AppTest.java:[2,6] cannot find symbol
  symbol:   class Test
  location: class AppTest
[ERROR] /root/mcw/test/src/test/java/com/jellythink/HelloWorld/AppTest.java:[6,9] cannot find symbol
  symbol:   method assertEquals(java.lang.String,java.lang.String)
  location: class AppTest
[INFO] 2 errors 
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  4.109 s
[INFO] Finished at: 2024-07-09T09:06:56+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project hello-world: Compilation failure: Compilation failure: 
[ERROR] /root/mcw/test/src/test/java/com/jellythink/HelloWorld/AppTest.java:[2,6] cannot find symbol
[ERROR]   symbol:   class Test
[ERROR]   location: class AppTest
[ERROR] /root/mcw/test/src/test/java/com/jellythink/HelloWorld/AppTest.java:[6,9] cannot find symbol
[ERROR]   symbol:   method assertEquals(java.lang.String,java.lang.String)
[ERROR]   location: class AppTest
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[root@mcw12 test]# cat /root/mcw/test/src/test/java/com/jellythink/HelloWorld/AppTest.java
public class AppTest {
    @Test
    public void testSayHello() {
        App app = new App();
        String result = app.sayHello();
        assertEquals("Hello World", result);
    }
}
[root@mcw12 test]# 

 

这个错误信息表明在 AppTest.java 文件的第6行,编译器无法找到 assertEquals 方法。这通常是因为以下几个原因之一:

  1. 缺少JUnit库:assertEquals 是JUnit测试框架中的一个方法,用于断言两个值是否相等。如果你的项目中没有包含JUnit库,那么编译器将无法识别这个方法。

  2. 导入错误:可能你的 AppTest.java 文件中没有正确地导入JUnit的 Assertions 类或者旧的JUnit版本中的 Assert 类。

  3. JUnit版本问题:不同的JUnit版本可能有不同的导入方式和类结构。例如,在JUnit 4中,assertEquals 方法位于 org.junit.Assert 类中,而在JUnit 5中,它位于 org.junit.jupiter.api.Assertions 类中。

解决方案

1. 添加JUnit依赖

确保你的项目中包含了JUnit的依赖。如果你是使用Maven,可以在 pom.xml 文件中添加如下依赖(以JUnit 5为例):

xml复制代码
  <dependency>
  <groupId>org.junit.jupiter</groupId>
  <artifactId>junit-jupiter-engine</artifactId>
  <version>5.7.0</version>
  <scope>test</scope>
  </dependency>

对于JUnit 4,依赖会是这样:

xml复制代码
  <dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.13.2</version>
  <scope>test</scope>
  </dependency>

2. 修正导入语句

根据你的JUnit版本,确保你导入了正确的类。对于JUnit 5,你应该在文件顶部添加:

java复制代码
  import org.junit.jupiter.api.Assertions;

然后你可以这样使用 assertEquals

java复制代码
  Assertions.assertEquals("expected", "actual");

或者,更常见的是静态导入:

java复制代码
  import static org.junit.jupiter.api.Assertions.assertEquals;

然后你可以直接使用 assertEquals

java复制代码
  assertEquals("expected", "actual");

对于JUnit 4,你应该导入:

java复制代码
  import static org.junit.Assert.assertEquals;

3. 检查项目配置

确保你的IDE或构建工具(如Maven或Gradle)已经正确设置了JUnit库。有时候,IDE的缓存或配置问题可能导致类路径不正确。

4. 清理和重建项目

尝试清理并重新构建你的项目。在Maven中,你可以使用以下命令:

添加导入之后又报错了

import static org.junit.Assert.assertEquals;

[root@mcw12 test]# cat src/test/java/com/jellythink/HelloWorld/AppTest.java
import static org.junit.Assert.assertEquals;
public class AppTest {
    @Test
    public void testSayHello() {
        App app = new App();
        String result = app.sayHello();
        assertEquals("Hello World", result);
    }
}
[root@mcw12 test]# mvn clean compile
[INFO] Scanning for projects...

 

[INFO] Compiling 1 source file to /root/mcw/test/target/test-classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR : 
[INFO] -------------------------------------------------------------
[ERROR] /root/mcw/test/src/test/java/com/jellythink/HelloWorld/AppTest.java:[3,6] cannot find symbol
  symbol:   class Test
  location: class AppTest
[INFO] 1 error
[INFO] -------------------------------------------------------------
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.374 s
[INFO] Finished at: 2024-07-09T09:14:03+08:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:testCompile (default-testCompile) on project hello-world: Compilation failure
[ERROR] /root/mcw/test/src/test/java/com/jellythink/HelloWorld/AppTest.java:[3,6] cannot find symbol
[ERROR]   symbol:   class Test
[ERROR]   location: class AppTest
[ERROR] 
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
[root@mcw12 test]# cat /root/mcw/test/src/test/java/com/jellythink/HelloWorld/AppTest.java
import static org.junit.Assert.assertEquals;
public class AppTest {
    @Test
    public void testSayHello() {
        App app = new App();
        String result = app.sayHello();
        assertEquals("Hello World", result);
    }
}
[root@mcw12 test]# vim src/test/java/com/jellythink/HelloWorld/AppTest.java 
[root@mcw12 test]# cat src/test/java/com/jellythink/HelloWorld/AppTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class AppTest {
    @Test
    public void testSayHello() {
        App app = new App();
        String result = app.sayHello();
        assertEquals("Hello World", result);
    }
}
[root@mcw12 test]# mvn clean compile

 

这个错误提示表明在 AppTest.java 文件的第3行,编译器无法找到名为 Test 的符号。这通常意味着 Test 类或接口没有被正确地导入到你的测试类中,或者它根本不存在于你的项目依赖中。但是,更常见的情况是,Test 可能是指 JUnit 测试框架中的 @Test 注解,而这个注解没有被正确导入。

解决方案

    1. 检查导入语句:
      确保你的 AppTest.java 文件中包含了正确的 JUnit 导入语句。如果你正在使用 JUnit 4,你应该有类似这样的导入:

      java复制代码
        import org.junit.Test;

添加导入之后就好了import org.junit.Test;

[root@mcw12 test]# cat src/test/java/com/jellythink/HelloWorld/AppTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class AppTest {
    @Test
    public void testSayHello() {
        App app = new App();
        String result = app.sayHello();
        assertEquals("Hello World", result);
    }
}
[root@mcw12 test]# mvn clean compile
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------< com.jellythink.HelloWorld:hello-world >----------------
[INFO] Building hello-world 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ hello-world ---
[INFO] Deleting /root/mcw/test/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ hello-world ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /root/mcw/test/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ hello-world ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /root/mcw/test/target/classes
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  2.066 s
[INFO] Finished at: 2024-07-09T09:15:56+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 test]# mvn clean package
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------< com.jellythink.HelloWorld:hello-world >----------------
[INFO] Building hello-world 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ hello-world ---
[INFO] Deleting /root/mcw/test/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ hello-world ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /root/mcw/test/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ hello-world ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /root/mcw/test/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ hello-world ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /root/mcw/test/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ hello-world ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /root/mcw/test/target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ hello-world ---
Downloading from central: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-booter/2.12.4/surefire-booter-2.12.4.pom
Downloaded from central: https://repo.maven.apache.org/maven2/org/apache/maven/surefire/surefire-booter/2.12.4/surefire-booter-2.12.4.pom (3.0 kB at 3.8 kB/s)
Downloaded from central: https://repo.maven.apache.org/maven2/org/codehaus/plexus/plexus-io/2.0.2/plexus-io-2.0.2.jar (58 kB at 362 kB/s)
[INFO] Building jar: /root/mcw/test/target/hello-world-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  8.157 s
[INFO] Finished at: 2024-07-09T09:16:11+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 test]# 

查看已经生成了jar包

[root@mcw12 test]# ls
pom.xml  src  target
[root@mcw12 test]# tree 
.
├── pom.xml
├── src
│   ├── main
│   │   └── java
│   │       └── com
│   │           └── jellythink
│   │               └── HelloWorld
│   │                   └── App.java
│   └── test
│       └── java
│           └── com
│               └── jellythink
│                   └── HelloWorld
│                       └── AppTest.java
└── target
    ├── classes
    │   └── App.class
    ├── generated-sources
    │   └── annotations
    ├── generated-test-sources
    │   └── test-annotations
    ├── hello-world-1.0-SNAPSHOT.jar
    ├── maven-archiver
    │   └── pom.properties
    ├── maven-status
    │   └── maven-compiler-plugin
    │       ├── compile
    │       │   └── default-compile
    │       │       ├── createdFiles.lst
    │       │       └── inputFiles.lst
    │       └── testCompile
    │           └── default-testCompile
    │               ├── createdFiles.lst
    │               └── inputFiles.lst
    ├── surefire-reports
    │   ├── AppTest.txt
    │   └── TEST-AppTest.xml
    └── test-classes
        └── AppTest.class

26 directories, 13 files
[root@mcw12 test]# ls target/
classes  generated-sources  generated-test-sources  hello-world-1.0-SNAPSHOT.jar  maven-archiver  maven-status  surefire-reports  test-classes
[root@mcw12 test]# 

 

测试了下,还是不能执行jar包

[root@mcw12 test]# ls target/
classes  generated-sources  generated-test-sources  hello-world-1.0-SNAPSHOT.jar  maven-archiver  maven-status  surefire-reports  test-classes
[root@mcw12 test]# stat target/hello-world-1.0-SNAPSHOT.jar 
  File: ‘target/hello-world-1.0-SNAPSHOT.jar’
  Size: 2163          Blocks: 8          IO Block: 4096   regular file
Device: fd00h/64768d    Inode: 51597369    Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2024-07-09 09:16:11.878807236 +0800
Modify: 2024-07-09 09:16:11.878807236 +0800
Change: 2024-07-09 09:16:11.878807236 +0800
 Birth: -
[root@mcw12 test]# java -jar target/hello-world-1.0-SNAPSHOT.jar 
no main manifest attribute, in target/hello-world-1.0-SNAPSHOT.jar
[root@mcw12 test]# 
[root@mcw12 test]# java target/hello-world-1.0-SNAPSHOT.jar 
Error: Could not find or load main class target.hello-world-1.0-SNAPSHOT.jar
Caused by: java.lang.ClassNotFoundException: target.hello-world-1.0-SNAPSHOT.jar
[root@mcw12 test]# 
[root@mcw12 test]# 
[root@mcw12 test]# ls
pom.xml  src  target
[root@mcw12 test]# mvn clean package
[INFO] Scanning for projects...
[INFO] 
[INFO] ---------------< com.jellythink.HelloWorld:hello-world >----------------
[INFO] Building hello-world 1.0-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ jar ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ hello-world ---
[INFO] Deleting /root/mcw/test/target
[INFO] 
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ hello-world ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /root/mcw/test/src/main/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ hello-world ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /root/mcw/test/target/classes
[INFO] 
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ hello-world ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /root/mcw/test/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ hello-world ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /root/mcw/test/target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ hello-world ---
[INFO] Surefire report directory: /root/mcw/test/target/surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.088 sec

Results :

Tests run: 1, Failures: 0, Errors: 0, Skipped: 0

[INFO] 
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ hello-world ---
[INFO] Building jar: /root/mcw/test/target/hello-world-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  3.608 s
[INFO] Finished at: 2024-07-09T09:31:27+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 test]# stat /root/mcw/test/target/hello-world-1.0-SNAPSHOT.jar
  File: ‘/root/mcw/test/target/hello-world-1.0-SNAPSHOT.jar’
  Size: 2163          Blocks: 8          IO Block: 4096   regular file
Device: fd00h/64768d    Inode: 51597377    Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2024-07-09 09:31:27.563259827 +0800
Modify: 2024-07-09 09:31:27.563259827 +0800
Change: 2024-07-09 09:31:27.563259827 +0800
 Birth: -
[root@mcw12 test]# java -jar /root/mcw/test/target/hello-world-1.0-SNAPSHOT.jar
no main manifest attribute, in /root/mcw/test/target/hello-world-1.0-SNAPSHOT.jar
[root@mcw12 test]# java /root/mcw/test/target/hello-world-1.0-SNAPSHOT.jar
Error: Could not find or load main class .root.mcw.test.target.hello-world-1.0-SNAPSHOT.jar
Caused by: java.lang.ClassNotFoundException: /root/mcw/test/target/hello-world-1/0-SNAPSHOT/jar
[root@mcw12 test]# 

 修改如下:

查看这个目录层级下主类是这个文件

ls target/classes/
App.class

[root@mcw12 test]# ls 
pom.xml  pom.xmlbak  src  target
[root@mcw12 test]# ls src/
main  test
[root@mcw12 test]# tree src/
src/
├── main
│   └── java
│       └── com
│           └── jellythink
│               └── HelloWorld
│                   └── App.java
└── test
    └── java
        └── com
            └── jellythink
                └── HelloWorld
                    └── AppTest.java

10 directories, 2 files
[root@mcw12 test]# ls target/
classes  generated-sources  generated-test-sources  hello-world-1.0-SNAPSHOT.jar  maven-archiver  maven-status  original-hello-world-1.0-SNAPSHOT.jar  surefire-reports  test-classes
[root@mcw12 test]# ls target/classes/
App.class
[root@mcw12 test]# 

新增build配置。

主类从这里开始不行

com.jellythink.HelloWorld.App

从这里APP就可以

[root@mcw12 test]# cat pom.xml
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.jellythink.HelloWorld</groupId>
  <artifactId>hello-world</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>hello-world</name>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>  
    <maven.compiler.target>1.8</maven.compiler.target>  
  </properties>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                            <!--mainClass>com.jellythink.HelloWorld.App</mainClass-->
                            <mainClass>App</mainClass>
                        </transformer>
                    </transformers>
                </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

</project>
[root@mcw12 test]#

不知道跟pom.xml有没有关系

<groupId>com.jellythink.HelloWorld</groupId> 。确认没有关系,这里好像就是个名字

上面主类直接写最后那个文件,打出来的包,可以正常运行

[root@mcw12 test]# java -jar target/hello-world-1.0-SNAPSHOT.jar
Hello World
[root@mcw12 test]# 

我们在pom.xml里面,将主类前面加上目录名,结果就又不想了,报错无法导入这个HelloWorld.App,也就是只需要App,不需要那个目录名字就行

[root@mcw12 test]# java -jar target/hello-world-1.0-SNAPSHOT.jar
Error: Could not find or load main class HelloWorld.App
Caused by: java.lang.ClassNotFoundException: HelloWorld.App
[root@mcw12 test]# tree src/main/
src/main/
└── java
    └── com
        └── jellythink
            └── HelloWorld
                └── App.java

4 directories, 1 file
[root@mcw12 test]# cat src/main/java/com/jellythink/HelloWorld/App.java 
public class App {
    public String sayHello() {
        return "Hello World";
    }

    public static void main( String[] args ) {
        System.out.println(new App().sayHello());
    }
}
[root@mcw12 test]# 

将上面的java程序改成spingboot 

将Java程序改造成Spring Boot应用是一个常见的需求,旨在简化开发、配置和部署过程。Spring Boot通过提供“自动配置”和“起步依赖”等功能,让开发者能够更快地构建和运行Spring应用。以下是将一个普通的Java程序改造成Spring Boot应用的基本步骤:

1. 引入Spring Boot依赖

首先,你需要在你的项目中引入Spring Boot的起步依赖(starter dependencies)。如果你使用的是Maven,可以在pom.xml文件中添加如下依赖(以Spring Boot Web Starter为例):

<dependencies>  
    <dependency>  
        <groupId>org.springframework.boot</groupId>  
        <artifactId>spring-boot-starter-web</artifactId>  
    </dependency>  
    <!-- 其他必要的依赖 -->  
</dependencies>  
  
<properties>  
    <spring-boot.version>2.5.2</spring-boot.version>  
    <maven.compiler.source>1.8</maven.compiler.source>  
    <maven.compiler.target>1.8</maven.compiler.target>  
</properties>  
  
<dependencyManagement>  
    <dependencies>  
        <dependency>  
            <groupId>org.springframework.boot</groupId>  
            <artifactId>spring-boot-dependencies</artifactId>  
            <version>${spring-boot.version}</version>  
            <type>pom</type>  
            <scope>import</scope>  
        </dependency>  
    </dependencies>  
</dependencyManagement>

 

 

2. 创建Spring Boot主类

接下来,你需要创建一个Spring Boot主类,该类通常包含一个main方法,用于启动Spring Boot应用。使用@SpringBootApplication注解标记该类,这个注解包含了@Configuration@EnableAutoConfiguration@ComponentScan注解。

package com.jellythink.helloworld;  
  
import org.springframework.boot.SpringApplication;  
import org.springframework.boot.autoconfigure.SpringBootApplication;  
  
@SpringBootApplication  
public class HelloWorldApplication {  
  
    public static void main(String[] args) {  
        SpringApplication.run(HelloWorldApplication.class, args);  
    }  
  
}

 

 

3. 迁移现有代码

将你的Java程序中的逻辑迁移到Spring Boot应用中。这通常意味着你需要将业务逻辑类作为Spring管理的Bean(通过@Component@Service@Repository等注解),并将它们注入到需要的地方。

例如,如果你有一个HelloWorldService类,你可以这样定义它:

package com.jellythink.helloworld.service;  
  
import org.springframework.stereotype.Service;  
  
@Service  
public class HelloWorldService {  
  
    public String sayHello() {  
        return "Hello, Spring Boot!";  
    }  
  
}

 

 

4. 创建REST Controller

如果你的应用是一个Web应用,你可以使用Spring MVC来创建RESTful Web服务。例如,创建一个HelloWorldController类来处理HTTP请求:

package com.jellythink.helloworld.controller;  
  
import com.jellythink.helloworld.service.HelloWorldService;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.web.bind.annotation.GetMapping;  
import org.springframework.web.bind.annotation.RestController;  
  
@RestController  
public class HelloWorldController {  
  
    private final HelloWorldService helloWorldService;  
  
    @Autowired  
    public HelloWorldController(HelloWorldService helloWorldService) {  
        this.helloWorldService = helloWorldService;  
    }  
  
    @GetMapping("/")  
    public String hello() {  
        return helloWorldService.sayHello();  
    }  
  
}

 

 

5. 配置文件(可选)

如果你的应用需要外部配置(如数据库连接信息),你可以在src/main/resources/application.propertiesapplication.yml文件中进行配置。

6. 运行和测试

现在,你可以运行你的Spring Boot应用(通过运行HelloWorldApplication类中的main方法或使用Maven/Gradle命令),并使用浏览器或Postman等工具测试你的RESTful服务。

7. 打包和部署

最后,你可以使用Maven或Gradle的打包命令将你的Spring Boot应用打包成一个可执行的JAR文件,然后部署到任何支持Java的服务器上。

以上就是将Java程序改造成Spring Boot应用的基本步骤。记得根据你的具体需求调整这些步骤。

 

@@@实操

注意看,属性下定义的键值对,应该可以在别处直接引用

 

打包的命令演示

mvn clean package spring-boot:repackage

[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src  target
[root@mcw12 demo1]# ls target/
classes               demo1-0.0.1-SNAPSHOT.war           generated-sources       maven-archiver  surefire-reports
demo1-0.0.1-SNAPSHOT  demo1-0.0.1-SNAPSHOT.war.original  generated-test-sources  maven-status    test-classes
[root@mcw12 demo1]# mvn clean package spring-boot:repackage
[INFO] Scanning for projects...
[INFO] 
[INFO] -------------------------< org.example:demo1 >--------------------------
[INFO] Building demo1 0.0.1-SNAPSHOT
[INFO]   from pom.xml
[INFO] --------------------------------[ war ]---------------------------------
[INFO] 
[INFO] --- maven-clean-plugin:3.3.2:clean (default-clean) @ demo1 ---
[INFO] Deleting /root/mcwversion/demo1/target
[INFO] 
[INFO] --- maven-resources-plugin:3.3.1:resources (default-resources) @ demo1 ---
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] Copying 1 resource from src/main/resources to target/classes
[INFO] 
[INFO] --- maven-compiler-plugin:3.13.0:compile (default-compile) @ demo1 ---
[INFO] Recompiling the module because of changed source code.
[INFO] Compiling 3 source files with javac [debug parameters release 17] to target/classes
[INFO] 
[INFO] --- maven-resources-plugin:3.3.1:testResources (default-testResources) @ demo1 ---
[INFO] skip non existing resourceDirectory /root/mcwversion/demo1/src/test/resources
[INFO] 
[INFO] --- maven-compiler-plugin:3.13.0:testCompile (default-testCompile) @ demo1 ---
[INFO] Recompiling the module because of changed dependency.
[INFO] Compiling 1 source file with javac [debug parameters release 17] to target/test-classes
[INFO] 
[INFO] --- maven-surefire-plugin:3.2.5:test (default-test) @ demo1 ---
[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider
[INFO] 
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.example.demo.Demo1ApplicationTests
09:53:17.699 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.demo.Demo1ApplicationTests]: Demo1ApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
09:53:18.097 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration com.example.demo.Demo1Application for test class com.example.demo.Demo1ApplicationTests

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.1)

2024-07-12T09:53:19.426+08:00  INFO 113491 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Starting Demo1ApplicationTests using Java 17.0.11 with PID 113491 (started by root in /root/mcwversion/demo1)
2024-07-12T09:53:19.428+08:00  INFO 113491 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : No active profile set, falling back to 1 default profile: "default"
2024-07-12T09:53:24.826+08:00  INFO 113491 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Started Demo1ApplicationTests in 6.398 seconds (process running for 9.371)
Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 10.45 s -- in com.example.demo.Demo1ApplicationTests
[INFO] 
[INFO] Results:
[INFO] 
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] 
[INFO] 
[INFO] --- maven-war-plugin:3.4.0:war (default-war) @ demo1 ---
[INFO] Packaging webapp
[INFO] Assembling webapp [demo1] in [/root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT]
[INFO] Processing war project
[INFO] Building war: /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war
[INFO] 
[INFO] --- spring-boot-maven-plugin:3.3.1:repackage (repackage) @ demo1 ---
[INFO] Replacing main artifact /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war with repackaged archive, adding nested dependencies in BOOT-INF/.
[INFO] The original artifact has been renamed to /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war.original
[INFO] 
[INFO] --- spring-boot-maven-plugin:3.3.1:repackage (default-cli) @ demo1 ---
[INFO] Replacing main artifact /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war with repackaged archive, adding nested dependencies in BOOT-INF/.
[INFO] The original artifact has been renamed to /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war.original
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  23.801 s
[INFO] Finished at: 2024-07-12T09:53:32+08:00
[INFO] ------------------------------------------------------------------------
[root@mcw12 demo1]# ls
HELP.md  mvnw  mvnw.cmd  pom.xml  src  target
[root@mcw12 demo1]# ls target/
classes               demo1-0.0.1-SNAPSHOT.war           generated-sources       maven-archiver  surefire-reports
demo1-0.0.1-SNAPSHOT  demo1-0.0.1-SNAPSHOT.war.original  generated-test-sources  maven-status    test-classes
[root@mcw12 demo1]# java -jar target/demo1-0.0.1-SNAPSHOT.war

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/

 :: Spring Boot ::                (v3.3.1)

2024-07-12T09:54:04.271+08:00  INFO 113589 --- [demo1] [           main] com.example.demo.Demo1Application        : Starting Demo1Application v0.0.1-SNAPSHOT using Java 17.0.11 with PID 113589 (/root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war started by root in /root/mcwversion/demo1)
2024-07-12T09:54:04.274+08:00  INFO 113589 --- [demo1] [           main] com.example.demo.Demo1Application        : No active profile set, falling back to 1 default profile: "default"
2024-07-12T09:54:06.763+08:00  INFO 113589 --- [demo1] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)
2024-07-12T09:54:06.789+08:00  INFO 113589 --- [demo1] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2024-07-12T09:54:06.789+08:00  INFO 113589 --- [demo1] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.25]
2024-07-12T09:54:07.063+08:00  INFO 113589 --- [demo1] [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2024-07-12T09:54:07.067+08:00  INFO 113589 --- [demo1] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2662 ms
2024-07-12T09:54:08.423+08:00  INFO 113589 --- [demo1] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
2024-07-12T09:54:08.468+08:00  INFO 113589 --- [demo1] [           main] com.example.demo.Demo1Application        : Started Demo1Application in 5.102 seconds (process running for 6.153)
2024-07-12T09:54:13.831+08:00  INFO 113589 --- [demo1] [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-07-12T09:54:13.831+08:00  INFO 113589 --- [demo1] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2024-07-12T09:54:13.832+08:00  INFO 113589 --- [demo1] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms

 

 

 

 

 

[root@mcw12 demo1]# lsHELP.md  mvnw  mvnw.cmd  pom.xml  src  target[root@mcw12 demo1]# ls target/classes               demo1-0.0.1-SNAPSHOT.war           generated-sources       maven-archiver  surefire-reportsdemo1-0.0.1-SNAPSHOT  demo1-0.0.1-SNAPSHOT.war.original  generated-test-sources  maven-status    test-classes[root@mcw12 demo1]# mvn clean package spring-boot:repackage[INFO] Scanning for projects...[INFO] [INFO] -------------------------< org.example:demo1 >--------------------------[INFO] Building demo1 0.0.1-SNAPSHOT[INFO]   from pom.xml[INFO] --------------------------------[ war ]---------------------------------[INFO] [INFO] --- maven-clean-plugin:3.3.2:clean (default-clean) @ demo1 ---[INFO] Deleting /root/mcwversion/demo1/target[INFO] [INFO] --- maven-resources-plugin:3.3.1:resources (default-resources) @ demo1 ---[INFO] Copying 1 resource from src/main/resources to target/classes[INFO] Copying 1 resource from src/main/resources to target/classes[INFO] [INFO] --- maven-compiler-plugin:3.13.0:compile (default-compile) @ demo1 ---[INFO] Recompiling the module because of changed source code.[INFO] Compiling 3 source files with javac [debug parameters release 17] to target/classes[INFO] [INFO] --- maven-resources-plugin:3.3.1:testResources (default-testResources) @ demo1 ---[INFO] skip non existing resourceDirectory /root/mcwversion/demo1/src/test/resources[INFO] [INFO] --- maven-compiler-plugin:3.13.0:testCompile (default-testCompile) @ demo1 ---[INFO] Recompiling the module because of changed dependency.[INFO] Compiling 1 source file with javac [debug parameters release 17] to target/test-classes[INFO] [INFO] --- maven-surefire-plugin:3.2.5:test (default-test) @ demo1 ---[INFO] Using auto detected provider org.apache.maven.surefire.junitplatform.JUnitPlatformProvider[INFO] [INFO] -------------------------------------------------------[INFO]  T E S T S[INFO] -------------------------------------------------------[INFO] Running com.example.demo.Demo1ApplicationTests09:53:17.699 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils -- Could not detect default configuration classes for test class [com.example.demo.Demo1ApplicationTests]: Demo1ApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.09:53:18.097 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper -- Found @SpringBootConfiguration com.example.demo.Demo1Application for test class com.example.demo.Demo1ApplicationTests
  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.3.1)
2024-07-12T09:53:19.426+08:00  INFO 113491 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Starting Demo1ApplicationTests using Java 17.0.11 with PID 113491 (started by root in /root/mcwversion/demo1)2024-07-12T09:53:19.428+08:00  INFO 113491 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : No active profile set, falling back to 1 default profile: "default"2024-07-12T09:53:24.826+08:00  INFO 113491 --- [demo1] [           main] com.example.demo.Demo1ApplicationTests   : Started Demo1ApplicationTests in 6.398 seconds (process running for 9.371)Java HotSpot(TM) 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 10.45 s -- in com.example.demo.Demo1ApplicationTests[INFO] [INFO] Results:[INFO] [INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0[INFO] [INFO] [INFO] --- maven-war-plugin:3.4.0:war (default-war) @ demo1 ---[INFO] Packaging webapp[INFO] Assembling webapp [demo1] in [/root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT][INFO] Processing war project[INFO] Building war: /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war[INFO] [INFO] --- spring-boot-maven-plugin:3.3.1:repackage (repackage) @ demo1 ---[INFO] Replacing main artifact /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war with repackaged archive, adding nested dependencies in BOOT-INF/.[INFO] The original artifact has been renamed to /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war.original[INFO] [INFO] --- spring-boot-maven-plugin:3.3.1:repackage (default-cli) @ demo1 ---[INFO] Replacing main artifact /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war with repackaged archive, adding nested dependencies in BOOT-INF/.[INFO] The original artifact has been renamed to /root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war.original[INFO] ------------------------------------------------------------------------[INFO] BUILD SUCCESS[INFO] ------------------------------------------------------------------------[INFO] Total time:  23.801 s[INFO] Finished at: 2024-07-12T09:53:32+08:00[INFO] ------------------------------------------------------------------------[root@mcw12 demo1]# lsHELP.md  mvnw  mvnw.cmd  pom.xml  src  target[root@mcw12 demo1]# ls target/classes               demo1-0.0.1-SNAPSHOT.war           generated-sources       maven-archiver  surefire-reportsdemo1-0.0.1-SNAPSHOT  demo1-0.0.1-SNAPSHOT.war.original  generated-test-sources  maven-status    test-classes[root@mcw12 demo1]# java -jar target/demo1-0.0.1-SNAPSHOT.war
  .   ____          _            __ _ _ /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/  ___)| |_)| | | | | || (_| |  ) ) ) )  '  |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.3.1)
2024-07-12T09:54:04.271+08:00  INFO 113589 --- [demo1] [           main] com.example.demo.Demo1Application        : Starting Demo1Application v0.0.1-SNAPSHOT using Java 17.0.11 with PID 113589 (/root/mcwversion/demo1/target/demo1-0.0.1-SNAPSHOT.war started by root in /root/mcwversion/demo1)2024-07-12T09:54:04.274+08:00  INFO 113589 --- [demo1] [           main] com.example.demo.Demo1Application        : No active profile set, falling back to 1 default profile: "default"2024-07-12T09:54:06.763+08:00  INFO 113589 --- [demo1] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port 8080 (http)2024-07-12T09:54:06.789+08:00  INFO 113589 --- [demo1] [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]2024-07-12T09:54:06.789+08:00  INFO 113589 --- [demo1] [           main] o.apache.catalina.core.StandardEngine    : Starting Servlet engine: [Apache Tomcat/10.1.25]2024-07-12T09:54:07.063+08:00  INFO 113589 --- [demo1] [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext2024-07-12T09:54:07.067+08:00  INFO 113589 --- [demo1] [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2662 ms2024-07-12T09:54:08.423+08:00  INFO 113589 --- [demo1] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'2024-07-12T09:54:08.468+08:00  INFO 113589 --- [demo1] [           main] com.example.demo.Demo1Application        : Started Demo1Application in 5.102 seconds (process running for 6.153)2024-07-12T09:54:13.831+08:00  INFO 113589 --- [demo1] [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'2024-07-12T09:54:13.831+08:00  INFO 113589 --- [demo1] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'2024-07-12T09:54:13.832+08:00  INFO 113589 --- [demo1] [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
 
posted @ 2024-07-07 22:04  马昌伟  阅读(48)  评论(0编辑  收藏  举报
博主链接地址:https://www.cnblogs.com/machangwei-8/