跳到内容

元数据卡

  • 前置知识:终端(ch02)、Git(ch03)、构建工具(ch05)、Docker(ch07)
  • 预计时间:12 分钟
  • 完成标志:能说出代码从编辑器到上线的完整链路

你的进度

装备齐全了。终端是你的武器,Git 是时光机,调试器是显微镜,构建工具是补给站——上一章你甚至学会了把整间工坊打包成 Docker 箱子。

你还站在工坊里,但门已经开了一条缝。工坊的师傅这次没有给你新工具——他指了指门外。

现在该上路了。前七章你一直在工坊里练刀。现在工坊的门打开了:你的第一行代码,要真正变成用户能访问的东西。


从零开始创建一个真实项目

工坊主人把你拉到一张空桌前。桌上什么都没有——没有代码,没有配置,只有一面墙的工具。"前七章你学会了每个工具单独怎么用,"他说,"现在把它们串起来。从空目录开始,走完全流程。"

他敲了敲桌面。"别说你没工具——终端、Git、Maven、Docker,全在架子上挂着。"

创建一个最简的 Spring Boot 项目,用命令行:

bash
# 创建目录结构
mkdir -p hello-atlas/src/main/java/com/example
mkdir -p hello-atlas/src/main/resources
cd hello-atlas

在项目根目录创建 pom.xml

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>
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>3.2.5</version>
 </parent>
 <groupId>com.example</groupId>
 <artifactId>hello-atlas</artifactId>
 <version>1.0.0</version>

 <dependencies>
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
 </dependency>
 </dependencies>
 <build>
 <plugins>
 <plugin>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-maven-plugin</artifactId>
 </plugin>
 </plugins>
 </build>
</project>

主应用类 src/main/java/com/example/HelloAtlasApplication.java

java
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class HelloAtlasApplication {

 public static void main(String[] args) {
 SpringApplication.run(HelloAtlasApplication.class, args);
 }

 @GetMapping("/")
 public String hello() {
 return "Hello Atlas! 出发!";
 }
}

配置文件 src/main/resources/application.properties

properties
server.port=8080

编译与运行

bash
mvn clean package -DskipTests
java -jar target/hello-atlas-1.0.0.jar

打开浏览器,输入 http://localhost:8080

看到 "Hello Atlas! 出发!" 了吗?

你刚走过了前两站:写代码 → 编译打包。那个 target/hello-atlas-1.0.0.jar 是一个 fat JAR——里面打包了所有依赖和嵌入式的 Tomcat 服务器。一个文件,就能跑。

容器化

把 JAR 装进 Docker 箱子。创建 Dockerfile

dockerfile
FROM eclipse-temurin:17-jdk-alpine
WORKDIR /app
COPY target/hello-atlas-1.0.0.jar app.jar
EXPOSE 8080
CMD ["java", "-jar", "app.jar"]
bash
docker build -t hello-atlas:v1 .
docker run -d -p 8080:8080 --name hello-atlas hello-atlas:v1

同样访问 localhost:8080


旅人笔记

从编辑器到可运行程序,你走过了五个阶段:写代码 → 编译打包 → 容器化 → 推送仓库 → 部署运行。每多走一个阶段,你的代码就离"真正被别人用"近了一步。

下一步:CI/CD——让机器替你走路

手动部署太累了。让 GitHub Actions 自动完成这一切。

学 CI/CD 自动化 →

Built with VitePress | Software Systems Atlas