如何生成适配Java 8、含JUnit 5+依赖的Maven Java项目?
当然有!不用再手动修改默认quickstart带来的老旧JUnit 3.8.1依赖和未指定的编译版本了,这里有几种实用方案帮你直接生成符合需求的Maven项目:
方案1:使用官方JUnit Jupiter原型(最省心)
Apache Maven提供了专门的JUnit Jupiter原型,它默认就配置了JUnit 5+的依赖,而且可以直接通过参数指定Java 8作为编译目标。执行这条命令即可:
mvn archetype:generate -DgroupId=com.example -DartifactId=start -DarchetypeArtifactId=maven-archetype-junit-jupiter -DinteractiveMode=false -Dmaven.compiler.source=8 -Dmaven.compiler.target=8
生成的项目会自动引入JUnit Jupiter的API和测试引擎依赖,测试类也是基于JUnit 5的标准写法(使用org.junit.jupiter.api.Test注解),完全满足你的兼容要求。
方案2:改造默认quickstart原型
如果你更习惯用经典的maven-archetype-quickstart,可以分两步调整:
- 生成时直接指定Java 8编译参数
执行这条命令生成基础项目,同时指定编译版本:
mvn archetype:generate -DgroupId=com.example -DartifactId=start -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false -Dmaven.compiler.source=8 -Dmaven.compiler.target=8
- 替换JUnit依赖为JUnit 5
打开生成的pom.xml,把原有的JUnit 3.8.1依赖删除,替换成JUnit Jupiter的依赖:
<dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.9.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.9.2</version> <scope>test</scope> </dependency> </dependencies>
另外记得配置maven-surefire-plugin,确保它能正确运行JUnit 5测试:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.1.2</version> </plugin> </plugins> </build>
方案3:自定义专属原型(适合频繁生成)
如果经常需要创建这类项目,你可以把配置好的模板项目打包成自己的Maven原型:
- 先搭建一个符合要求的项目(配置好JUnit 5、Java 8编译目标)
- 在项目根目录执行
mvn archetype:create-from-project - 进入生成的
target/generated-sources/archetype目录,执行mvn install - 之后就可以用自己的archetype ID来快速生成同类项目了
内容的提问来源于stack exchange,提问作者Ole
相关产品推荐
相关产品推荐

