java程序 如何发布
打包 Java 程序
Java 程序通常通过 JAR(Java Archive)或 WAR(Web Archive)文件打包。使用 Maven 或 Gradle 构建工具可以简化打包过程。
Maven 打包命令:
mvn package
生成的 JAR 文件位于 target/ 目录下。
手动打包 JAR:
jar cvf program.jar -C classes/ .
classes/ 是编译后的 .class 文件目录。
配置主类
在 MANIFEST.MF 中指定主类(含 main 方法):
Main-Class: com.example.Main
通过 Maven 插件自动配置:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.example.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
依赖管理
确保依赖库包含在发布的包中。使用 Maven 的 maven-assembly-plugin 生成包含依赖的 JAR:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
运行 mvn assembly:single 生成含依赖的 JAR。
发布到本地或远程仓库
Maven 发布到本地仓库:
mvn install
发布到远程仓库(如 Nexus):
mvn deploy
需在 pom.xml 中配置仓库地址:
<distributionManagement>
<repository>
<id>nexus-releases</id>
<url>http://nexus.example.com/repository/maven-releases</url>
</repository>
</distributionManagement>
生成可执行文件(可选)
使用工具如 jpackage(JDK 14+)生成平台特定的安装包:
jpackage --input target/ --name MyApp --main-jar program.jar
支持生成 .exe、.dmg 或 .deb 等格式。
容器化部署(Docker)
创建 Dockerfile 运行 JAR 文件:
FROM openjdk:17
COPY target/program.jar /app/program.jar
ENTRYPOINT ["java", "-jar", "/app/program.jar"]
构建并运行容器:
docker build -t my-java-app .
docker run -p 8080:8080 my-java-app
云平台部署
- AWS:通过 Elastic Beanstalk 或 ECS 部署 JAR 或 Docker 镜像。
- Azure:使用 Azure App Service 或 AKS。
- Google Cloud:通过 App Engine 或 GKE 部署。
每种方法需根据平台文档配置部署描述文件(如 app.yaml 或 Dockerfile)。






