難以置信!我用一個 Java 類替換了整個后端,還真的跑起來了
在軟件開發領域,我們往往被各種框架、層次化架構、復雜的配置文件包圍。Spring Boot、微服務、DTO、Mapper、Docker……這些東西很強大,但在某些小項目里,它們帶來的復雜度可能遠遠超過了項目本身。
我曾經突然冒出一個瘋狂的想法:如果只用一個 Java 類,就能實現一個完整的后端服務,會怎么樣?
聽上去像笑話,對吧?結果我真的試了一下,意外發現:不僅能跑,而且對快速驗證原型非常好用。 當然,這不是鼓勵大家拋棄架構,而是一次“去除繁雜、回歸本質”的嘗試。正如一句老話說的:“大道至簡。”
故事的起點
一切從一個小型的筆記應用開始。需求極其簡單:
- 保存筆記
- 獲取筆記
- 修改筆記
- 刪除筆記
換句話說,就是一個標準的 CRUD 系統。 按照傳統做法,我會:
- 起一個 Spring Boot 項目
- 定義實體、DAO、Service、Controller
- 加 DTO、Mapper
- 寫配置文件
- Docker 打包部署
但這對一個微型項目來說,顯然是“大炮打蚊子”。于是我自問:
“能不能用一個類就把這些搞定,而且還能保持一定的可維護性?”
執行計劃
我設定了幾個原則:
- 使用 Java 自帶的 HttpServer(不依賴 Spring Boot)
- 數據存儲放內存里,用一個 Map 就夠
- 所有邏輯放進一個類,但結構要清晰
- 提供標準 RESTful 接口,前端能直接消費
目錄結構非常干凈:
/projects/one-class-backend/src/main/java/com/icoderoad/notes/NoteServer.java單類后端實現
package com.icoderoad.notes;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class NoteServer {
private static Map<Integer, String> notes = new HashMap<>();
private static int idCounter = 1;
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/notes", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
String method = exchange.getRequestMethod();
switch (method) {
case "GET":
handleGet(exchange);
break;
case "POST":
handlePost(exchange);
break;
case "PUT":
handlePut(exchange);
break;
case "DELETE":
handleDelete(exchange);
break;
default:
exchange.sendResponseHeaders(405, -1);
}
}
});
server.setExecutor(null);
server.start();
System.out.println("Server started on port 8080");
}
private static void handleGet(HttpExchange exchange) throws IOException {
String response = notes.entrySet()
.stream()
.map(e -> e.getKey() + ": " + e.getValue())
.collect(Collectors.joining("\n"));
sendResponse(exchange, response);
}
private static void handlePost(HttpExchange exchange) throws IOException {
String body = new String(exchange.getRequestBody().readAllBytes());
notes.put(idCounter++, body);
sendResponse(exchange, "Note added");
}
private static void handlePut(HttpExchange exchange) throws IOException {
String[] parts = new String(exchange.getRequestBody().readAllBytes()).split(":", 2);
int id = Integer.parseInt(parts[0].trim());
String note = parts[1].trim();
if (notes.containsKey(id)) {
notes.put(id, note);
sendResponse(exchange, "Note updated");
} else {
sendResponse(exchange, "Note not found");
}
}
private static void handleDelete(HttpExchange exchange) throws IOException {
String body = new String(exchange.getRequestBody().readAllBytes());
int id = Integer.parseInt(body.trim());
if (notes.remove(id) != null) {
sendResponse(exchange, "Note deleted");
} else {
sendResponse(exchange, "Note not found");
}
}
private static void sendResponse(HttpExchange exchange, String response) throws IOException {
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}運行邏輯解析
內置 HTTP 服務器
HttpServer 來自 com.sun.net.httpserver,無需任何第三方依賴:
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);瞬間就能起一個 8080 端口的 HTTP 服務。
請求路由
所有 /notes 請求走一個 HttpHandler,再根據 GET/POST/PUT/DELETE 分發。
內存存儲
private static Map<Integer, String> notes = new HashMap<>();每條筆記有一個自增 ID,完全夠小項目用了。
CRUD 邏輯
- POST → 新增筆記
- GET → 查詢筆記列表
- PUT → 修改筆記內容
- DELETE → 刪除指定 ID 的筆記
測試接口
# 新增筆記
curl -X POST http://localhost:8080/notes -d "買牛奶"
# 獲取所有筆記
curl http://localhost:8080/notes
# 修改筆記
curl -X PUT http://localhost:8080/notes -d "1: 買咖啡"
# 刪除筆記
curl -X DELETE http://localhost:8080/notes -d "1"收獲與不足
優點:
- 啟動極快(100ms 內)
- 無框架開銷,零依賴
- 部署就是一個 .class 文件
- 非常適合原型開發
缺點:
- 無持久化,重啟數據丟失
- 無鑒權,誰都能訪問
- 無校驗,臟數據隨便進
- 不適合高并發
潛在改進方案
- 引入 SQLite 文件存儲
- 加上基礎 Token 鑒權
- 返回 JSON 格式,而不是純文本
- 增強錯誤處理機制
適用場景
可以用的地方:
- Hackathon 快速原型
- Demo 演示
- 本地小工具
- 教學/實驗
不推薦的地方:
- 企業級系統
- 高流量網站
- 涉及敏感數據的場景
經驗總結
這次實驗讓我重新認識了 Java:
- 框架固然重要,但 Java 本身就足夠強大
- 小項目過度設計,往往是浪費時間
- 簡單起步,再逐步復雜化,往往比一上來就堆滿技術更高效
結語
我不會真的在生產里上一個“單類后端”,畢竟架構是為了長遠穩定。但這個過程提醒我:有時候最好的解決方案,就是去掉那些不必要的復雜性。
下次當你要做一個小工具時,別急著起 Spring Boot。 也許,一個 NoteServer.java 就能讓你秒起后端。
今天就講到這里,如果有問題需要咨詢,大家可以直接留言或掃下方二維碼來知識星球找我,我們會盡力為你解答。





























