נבנה על ידיBuilt by Ariel Yohimovich

JavaJava
40
חלקPart 7: Java בעולם האמיתיJava in the real world כ-3 שעות (כולל הפסקה)About 3 hours (with a break)

Spring Boot REST עם בדיקותSpring Boot REST with tests

פרויקט Spring Boot, controller, service ו-repository, JSON אוטומטי, ובדיקות עם MockMvc.

A Spring Boot project, controller, service and repository, automatic JSON, and tests with MockMvc.

01המונחים של המפגשThis session's terms

לפני הקוד, המילים. כל מונח כאן מקושר גם במילון של הקורס.

Before the code, the words. Every term here is also linked in the course glossary.

  • REST: סגנון API מעל HTTP: כל דבר הוא משאב בכתובת (/books/Dune), והשיטה אומרת מה עושים: GET קורא, POST יוצר, PUT מעדכן, DELETE מוחק.REST: An API style over HTTP: everything is a resource at an address (/books/Dune), and the method says what to do: GET reads, POST creates, PUT updates, DELETE deletes.
  • Spring Boot: framework שמרים שרת אינטרנט ב-Java בכמה שורות. מחלקה עם @RestController ומתודות עם @GetMapping("/books") הופכות לנקודות קצה.Spring Boot: A framework that starts a Java web server in a few lines. A class with @RestController and methods with @GetMapping("/books") become endpoints.
  • שכבות: controller מדבר HTTP (בקשה ותשובה), service מחזיק את הכללים, ו-repository שומר נתונים. כל שכבה מדברת רק עם זו שמתחתיה.layers: The controller speaks HTTP (request and response), the service holds the rules, and the repository stores data. Each layer talks only to the one below.
  • נקודת קצה: שילוב של שיטה וכתובת שהשרת עונה לו, למשל GET /books/{title}.endpoint: A method-and-address pair the server answers, e.g. GET /books/{title}.
  • הזרקת תלויות: מחלקה מקבלת את מה שהיא צריכה בבנאי, במקום ליצור אותו. ב-Spring זה קורה לבד; כאן כותבים new BookController(new BookService(repo)).dependency injection: A class receives what it needs in its constructor, instead of creating it. In Spring that happens for you; here we write new BookController(new BookService(repo)).

02שרת REST ב-Spring BootA REST server in Spring Boot

שלוש נקודות קצה: כל הספרים, ספר לפי כותר (או 404), והוספה (201). Spring ממיר את ה-record ל-JSON לבד.

Three endpoints: every book, a book by title (or 404), and adding (201). Spring turns the record into JSON for you.

ShelfApp.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

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

record Book(String title, String author, int year) {
}

@RestController
@RequestMapping("/books")
class BookController {
    private final Map<String, Book> books = new ConcurrentHashMap<>();

    @GetMapping
    List<Book> all() {
        return List.copyOf(books.values());
    }

    @GetMapping("/{title}")
    ResponseEntity<Book> one(@PathVariable String title) {
        Book b = books.get(title);
        return b == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(b);
    }

    @PostMapping
    ResponseEntity<Book> add(@RequestBody Book b) {
        books.put(b.title(), b);
        return ResponseEntity.status(201).body(b);
    }
}
להרצה במחשב שלכםRun it on your computer

להרצה במחשב שלכם: Spring Boot הוא ספרייה חיצונית (יוצרים פרויקט ב-start.spring.io או ב-IntelliJ, ומריצים mvn spring-boot:run). אחר כך: curl localhost:8080/books. כאן הקוד מוצג בלי הרצה.

Run it on your computer: Spring Boot is an external library (create a project at start.spring.io or in IntelliJ, then run mvn spring-boot:run). Then: curl localhost:8080/books. Here the code is shown without running.

03אותן שכבות, ב-Java רגילהThe same layers, in plain Java

כדי לראות מה Spring עושה בשבילכם: Request נכנס ל-controller, שמחליט לפי שיטה וכתובת, קורא ל-service, שקורא ל-repository. התשובה היא סטטוס ו-JSON. הכול כאן רץ באמת.

To see what Spring does for you: a Request enters the controller, which decides by method and address, calls the service, which calls the repository. The answer is a status and JSON. Everything here really runs.

Main.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

public class Main {
    public static void main(String[] args) {
        BookController api = new BookController(new BookService(new BookRepository()));
        System.out.println(api.handle(new Request("POST", "/books", "Dune;Herbert;1965")));
        System.out.println(api.handle(new Request("GET", "/books/Dune", "")));
        System.out.println(api.handle(new Request("GET", "/books/Hamlet", "")));
        System.out.println(api.handle(new Request("GET", "/books", "")));
    }
}

class BookRepository {
    private final Map<String, Book> rows = new LinkedHashMap<>();

    void save(Book b) {
        rows.put(b.title(), b);
    }

    Book find(String title) {
        return rows.get(title);
    }

    List<Book> all() {
        return new ArrayList<>(rows.values());
    }
}

class BookService {
    private final BookRepository repo;

    BookService(BookRepository repo) {
        this.repo = repo;
    }

    Book add(String title, String author, int year) {
        if (year < 0) {
            throw new IllegalArgumentException("year must be >= 0");
        }
        Book b = new Book(title, author, year);
        repo.save(b);
        return b;
    }

    Book find(String title) {
        return repo.find(title);
    }

    List<Book> all() {
        return repo.all();
    }
}

class BookController {
    private final BookService service;

    BookController(BookService service) {
        this.service = service;
    }

    Response handle(Request r) {
        if (r.method().equals("GET") && r.path().equals("/books")) {
            StringJoiner arr = new StringJoiner(", ", "[", "]");
            for (Book b : service.all()) {
                arr.add(b.json());
            }
            return new Response(200, arr.toString());
        }
        if (r.method().equals("GET") && r.path().startsWith("/books/")) {
            Book b = service.find(r.path().substring("/books/".length()));
            return b == null ? new Response(404, "{\"error\": \"not found\"}") : new Response(200, b.json());
        }
        if (r.method().equals("POST") && r.path().equals("/books")) {
            String[] f = r.body().split(";");
            try {
                return new Response(201, service.add(f[0], f[1], Integer.parseInt(f[2])).json());
            } catch (IllegalArgumentException e) {
                return new Response(400, "{\"error\": \"" + e.getMessage() + "\"}");
            }
        }
        return new Response(405, "{\"error\": \"method not allowed\"}");
    }
}

record Request(String method, String path, String body) {
}

record Response(int status, String body) {
    @Override
    public String toString() {
        return status + " " + body;
    }
}

record Book(String title, String author, int year) {
    String json() {
        return "{\"title\": \"" + title + "\", \"author\": \"" + author + "\", \"year\": " + year + "}";
    }
}
פלטOutput
201 {"title": "Dune", "author": "Herbert", "year": 1965}
200 {"title": "Dune", "author": "Herbert", "year": 1965}
404 {"error": "not found"}
200 [{"title": "Dune", "author": "Herbert", "year": 1965}]
צפו בהרצה צעד אחר צעדWatch it run, step by step
צפו בהרצהWatch it runשורה אחרי שורה, כמו ש-Java מבצעתLine by line, the way Java runs it

מה קורה עכשיוWhat happens now

הקופסאות (משתנים)The boxes (variables)

מסך הפלטOutput screen

04הצעד של היום בפרויקט מדףToday's step in the Shelf project

הרחיבו את השכבות: POST עם שנה שלילית מחזיר 400 (ה-service זורק, ה-controller ממיר ל-400), ושיטה לא מוכרת (DELETE) מחזירה 405. הפלט: 201, 200, 404, 400, 201, 200 עם שני ספרים, 405.

Extend the layers: a POST with a negative year returns 400 (the service throws, the controller turns it into 400), and an unknown method (DELETE) returns 405. The output: 201, 200, 404, 400, 201, 200 with two books, 405.

טיפTip

את הצעד הזה כותבים בעמוד התרגול (התרגיל המסומן כצעד בפרויקט). בעמוד הפתרונות יש פתרון מלא עם סימולציה שמריצה אותו.

You write this step on the practice page (the exercise marked as a project step). The solutions page has a full solution with a simulation that runs it.

סיימתם את ההרצאה!Lecture complete!

עכשיו המצגת לחזרה מהירה, או ישר לתרגול.

Next: the slides for a quick review, or straight to practice.

נבנה על ידיBuilt by Ariel Yohimovich