From 8cced1f779d89fe603db2dd888e2d56219729aa3 Mon Sep 17 00:00:00 2001 From: Justin Yoo Date: Sun, 1 Jun 2025 02:04:20 +0900 Subject: [PATCH] Update Java doc with custom instructions --- README.md | 3 + docs/01-python.md | 4 +- docs/02-javascript.md | 2 +- docs/03-java.md | 254 +++++++----------- docs/04-dotnet.md | 3 +- .../java/copilot-instructions.md | 92 +++++++ 6 files changed, 196 insertions(+), 162 deletions(-) create mode 100644 docs/custom-instructions/java/copilot-instructions.md diff --git a/README.md b/README.md index fa52850..3c52efe 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,9 @@ During this workshop, [GitHub Codespaces](https://docs.github.com/ko/codespaces/ - [SDKMAN](https://sdkman.io/) - [OpenJDK 21](https://learn.microsoft.com/java/openjdk/download) through SDKMAN +- [Apache Maven](https://maven.apache.org/download.cgi) through SDKMAN +- [Gradle Build Tool](https://docs.gradle.org/current/userguide/installation.html) through SDKMAN +- [Spring Boot Initializr](https://docs.spring.io/spring-boot/cli/installation.html) through SDKMAN - VS Code [Extension Pack for Java](https://marketplace.visualstudio.com/items/?itemName=vscjava.vscode-java-pack) Extension - VS Code [Spring Boot Extension Pack](https://marketplace.visualstudio.com/items/?itemName=vmware.vscode-boot-dev-pack) Extension diff --git a/docs/01-python.md b/docs/01-python.md index f74f7ae..60558d7 100644 --- a/docs/01-python.md +++ b/docs/01-python.md @@ -88,7 +88,7 @@ Refer to the [README](../README.md) doc for preparation. - Use in-memory feature of SQLite. - The database should always be initialized whenever starting the app. - Use `openapi.yaml` that describes all the endpoints and data schema. - - Use the port number of `5050`. + - Use the port number of `8000`. - Entrypoint is `main.py`. - The API application should render Swagger UI page through a default endpoint. - The API application should render exactly the same OpenAPI document through a default endpoint. @@ -105,7 +105,7 @@ Refer to the [README](../README.md) doc for preparation. If app running fails, analyze the issues and fix them. ``` -1. Open a web browser and navigate to `http://localhost:5050`. +1. Open a web browser and navigate to `http://localhost:8000`. 1. Click the `[keep]` button of GitHub Copilot to take the changes. --- diff --git a/docs/02-javascript.md b/docs/02-javascript.md index 9b189bf..354de5b 100644 --- a/docs/02-javascript.md +++ b/docs/02-javascript.md @@ -74,7 +74,7 @@ Refer to the [README](../README.md) doc for preparation. - Use ViteJS as the frontend app framework. - Use default settings when initializing the project. - Use `SimpleSocialMediaApplication` as the name of the project while initializing. - - Use the port number of `3030`. + - Use the port number of `3000`. ``` ### Set-up Figma MCP Server diff --git a/docs/03-java.md b/docs/03-java.md index bef40ef..3e5a74f 100644 --- a/docs/03-java.md +++ b/docs/03-java.md @@ -1,196 +1,134 @@ # 03: Java Migration from Python -## 시나리오 +## Scenario -Contoso 아웃도어 컴파니의 마케팅 팀에서는 제품 홍보를 위한 마이크로 소셜 미디어 웹사이트를 빠르게 론칭하고 싶어 합니다. +Contoso is a company that sells products for various outdoor activities. A marketing department of Contoso would like to launch a micro social media website to promote their products for existing and potential customers. -Python 개발자가 백엔드 API를 개발하고 있었습니다만, 개인적인 사정으로 인해 회사를 그만두게 되었습니다! 개발팀의 Java 개발자인 당신은 이 Python 백엔드 API를 Java 기반의 Spring Boot 앱으로 마이그레이션을 해야 합니다. +Because a Python developer has left the company, the stakeholders asked to migrate the existing Python backend API app to Java, using Spring Boot. -## 사전 준비사항 +Now, as a Java developer, you should migrate the existing FastAPI app to Spring Boot. You've got very little knowledge of Python and FastAPI, by the way. -[README](../README.md) 문서를 참조하여 개발 환경을 준비합니다. +## Prerequisites -## 순서 +Refer to the [README](../README.md) doc for preparation. -- [개발 과정 프롬프트](#개발-과정-프롬프트) - - [프론트엔드 앱 및 백엔드 앱 확인](#프론트엔드-앱-및-백엔드-앱-확인) - - [프론트엔드 앱 및 백엔드 앱 실행 확인](#프론트엔드-앱-및-백엔드-앱-실행-확인) - - [REST API 확인](#rest-api-확인) - - [Python 앱 로직 확인](#python-앱-로직-확인) - - [Spring Boot 앱으로 마이그레이션](#spring-boot-앱으로-마이그레이션) - - [Spring Boot 프로젝트 생성](#spring-boot-프로젝트-생성) - - [빌드 및 앱 구동](#빌드-및-앱-구동) - - [REST API 추가 및 확인](#rest-api-추가-및-확인) - - [Python에 작성된 REST API 추가](#python에-작성된-rest-api-추가) - - [Database URL 변경](#database-url-변경) - - [백엔드 앱 전환 및 확인](#백엔드-앱-전환-및-확인) - - [확인](#확인) +## Getting Started -## 개발 과정 프롬프트 +- [Check GitHub Copilot Agent Mode](#check-github-copilot-agent-mode) +- [Prepare Custom Instructions](#prepare-custom-instructions) +- [Prepare Spring Boot Project](#prepare-spring-boot-project) +- [Migrate FastAPI API App](#migrate-fastapi-api-app) -Python 앱으로부터 Spring Boot 앱으로의 전체적인 마이그레이션 과정은 다음과 같습니다. +### Check GitHub Copilot Agent Mode -* [프론트엔드 앱 및 백엔드 앱 확인](#프론트엔드-앱-및-백엔드-앱-확인) -* [Spring Boot 앱으로 마이그레이션](#spring-boot-앱으로-마이그레이션) -* [백엔드 앱 전환 및 확인](#백엔드-앱-전환-및-확인) +1. Click the GitHub Copilot icon on the top of GitHub Codespace or VS Code and open GitHub Copilot window. -### 프론트엔드 앱 및 백엔드 앱 확인 + ![Open GitHub Copilot Chat](./images/setup-02.png) -#### 프론트엔드 앱 및 백엔드 앱 실행 확인 +1. If you're asked to login or sign up, do it. It's free of charge. +1. Make sure you're using GitHub Copilot Agent Mode. -이전 세션들에서 수행했던 Python 백엔드 앱 및 Node JS 프론트엔드 앱이 실행되어 있어야 합니다. 특히, Python 백엔드 앱을 기준으로 마이그레이션이 이루어지기 때문에 [http://127.0.0.1:8000/docs](http://127.0.0.1:8000/docs)에 접속하여 해당 앱이 구동되어 있는지를 확인합니다. + ![GitHub Copilot Agent Mode](./images/setup-03.png) -만일, 앱이 실행되어 있지 않다면, [Python 앱 가이드](../01-python.md)에 따라 앱을 구동해 주시기 바랍니다. +1. Select model to either `GPT-4.1` or `Claude Sonnet 4`. -#### REST API 확인 +### Prepare Custom Instructions -다음 URL을 호출하여 백엔드 앱에서 제공하고 있는 REST API들을 확인해 봅니다. 아래와 같이 12개의 REST API가 있는 것을 확인할 수 있습니다. +1. Set the environment variable of `$REPOSITORY_ROOT`. -``` -http://127.0.0.1:8000/docs -``` + ```bash + # bash/zsh + REPOSITORY_ROOT=$(git rev-parse --show-toplevel) + ``` -#### Python 앱 로직 확인 + ```powershell + # PowerShell + $REPOSITORY_ROOT = git rev-parse --show-toplevel + ``` -Python 앱에 어떤 기능들이 포함되어 있는지 확인하기 위해 GitHub Copilot에 다음과 같이 질의합니다. 해당 기능을 확인하여 대략의 Python 로직을 이해하고 파일을 생성합니다. +1. Copy custom instructions. -``` -이 파일의 소스 내용을 설명해 주고 다이어그램을 생성해줘 -``` + ```bash + # bash/zsh + cp -r $REPOSITORY_ROOT/docs/custom-instructions/java/. \ + $REPOSITORY_ROOT/.github/ + ``` -다음 위치에 다이어그램 파일이 생성된 것을 확인합니다. + ```powershell + # PowerShell + Copy-Item -Path $REPOSITORY_ROOT/docs/custom-instructions/java/* ` + -Destination $REPOSITORY_ROOT/.github/ -Recurse -Force + ``` -``` -.../python/diagram.md -``` +### Prepare Spring Boot Project -### Spring Boot 앱으로 마이그레이션 +1. Make sure that you're using GitHub Copilot Agent Mode with the model of `Claude Sonnet 4` or `GPT-4.1`. +1. Install Spring Boot CLI. -이제 Spring Boot 앱으로 마이그레이션 할 준비가 되었습니다. 이제부터 GitHub Copilot을 이용하여 마이그레이션을 진행하겠습니다. 이후 질의과정은 예시일 뿐이므로, 본인의 상황에 맞게 변경하여 질의하며 마이그레이션을 진행해도 됩니다. + ```bash + sdk install springboot + ``` -#### Spring Boot 프로젝트 생성 +1. Use prompt like below to scaffold a Spring Boot app project. -Spring Boot Initializr를 이용하면 Spring Boot 앱을 쉽게 생성할 수 있습니다. Spring Initializr 익스텐션을 사용하여 VS Code에서 초기 프로젝트를 생성해 보도록 합니다. 설정 값은 다음과 같습니다. + ```text + I'd like to scaffold a Spring Boot app. Follow the instructions below. -* 프로젝트 선택: Create a Gradle Project -* Spring Boot Version: 3.4.4 -* Project language: Java -* Group Id: com.example -* Artifact Id: demo -* Package Name: com.example.demo -* Packaging type: Jar -* Java version: 21 -* Dependencies: - * Spring Web - * Spring Boot Actuator - * Lombok + - Your working directory is `java`. + - Identify all the steps first, which is you're going to do. + - Use Spring Boot CLI to create the Spring Boot app project. + - Use Gradle as the Java package manager. + - Use the package name of `com.contoso.springapp`. + - Use the artifact ID of `springapp`. + - Use the group ID of `com.contoso`. + - Use the package type of `jar`. + - Use OpenJDK version of `21`. + - Add dependencies - `Spring Web`, `Spring Boot Actuator` and `Lombok`. + - Use the port number of `8080`. + - Build the Spring Boot app and verify if the app is built properly. + - Run this Spring Boot app and verify if the app is running properly. + - If either building or running the app fails, analyze the issues and fix them. + ``` -초기 Spring Boot 앱 프로젝트가 생성되었으면 우측 하단에의 "Open new project"를 클릭하여 방금 생성한 프로젝트를 오픈합니다. +1. Click the `[keep]` button of GitHub Copilot to take the changes. -![그림](images/java01.png) +### Migrate FastAPI API App -#### 빌드 및 앱 구동 +1. Make sure that you're using GitHub Copilot Agent Mode with the model of `Claude Sonnet 4` or `GPT-4.1`. +1. Add [`product-requirements.md`](../product-requirements.md) and [`openapi.yaml`](../openapi.yaml) to GitHub Copilot. +1. Use prompt like below to migrate FastAPI to Spring Boot. -최초 생성된 앱이 에러가 없는지 빌드 후 앱 구동을 통해 확인해 봅니다. + ```text + Now, we're migrating the existing FastAPI-based API app to Spring Boot API app. Carefully read the entire PRD and `openapi.yaml`. Follow the instructions below for the migration. + + - The existing FastAPI application is located at `python`. + - Your working directory is `java/springapp`. + - Identify all the steps first, which is you're going to do. + - Analyze the application structure of the existing FastAPI app. + - Migrate all the endpoints. Both corresponding endpoints should be exactly the same as each other. + - Use SQLite as the database. + - Use in-memory feature of SQLite. + - The database should always be initialized whenever starting the app. + - Use `openapi.yaml` that describes all the endpoints and data schema. + - The API application should render Swagger UI page through a default endpoint. + - The API application should render exactly the same OpenAPI document through a default endpoint. + - DO NOT add anything not defined in `openapi.yaml`. + - DO NOT modify anything defined in `openapi.yaml`. + - If necessary, add more packages for OpenAPI and Swagger UI. + ``` -``` -./gradlew clean build bootRun -``` +1. Click the `[keep]` button of GitHub Copilot to take the changes. +1. Once the application is built, verify if it's written properly or not. -터미널에 다음과 같은 로그가 출력되면 앱이 정상적으로 구동된 것입니다. + ```text + Run the Spring Boot app and verify if the app is properly running. Also verify the OpenAPI endpoint renders exactly the same content as `openapi.yaml`. -![그림](images/java02.png) - -#### REST API 추가 및 확인 - -디펜던시가 에러 없이 잘 추가되었는지 확인하기 위해 RestController를 추가해 봅니다. 기본 호출할 REST API로 /hello 를 생성해 보겠습니다. GitHub Copilot을 Agent 모드로 변경하고, 모델을 "Claude 3.7 Sonnet"으로 변경한 후 다음과 같이 프롬프트를 입력합니다. - -``` -/hello REST API를 추가해주고, Swagger 설정도 추가해줘 -``` - -다시 한 번 앱을 빌드하고 실행시켜 봅니다. - -코드에 오류가 없으면 다음 URL을 이용하여 앱을 호출해 봅니다. - -``` -http://localhost:8080/hello -``` - -이번에는 Swagger UI를 접속해 봅니다. - -``` -http://localhost:8080/swagger-ui.html -``` - -앱이 정상적으로 호출되었으면 마이그레이션 준비가 완료된 것입니다. - -#### Python에 작성된 REST API 추가 - -Python 앱은 12개의 REST API로 이루어진 백엔드 서비스로 구성되어 있습니다. 이제 좀 전에 생성한 다이어그램 파일을 활용하여 이 REST API를 자바로 변경해 보겠습니다. - -GitHub Copilot에 다음과 같이 프롬프트를 입력합니다. - -``` -이 다이어그램 파일을 참고해서 동일한 API 주소를 갖는 함수들을 현재 프로젝트에 추가해줘. -``` - -앱을 빌드하고, Swagger UI에 접속해서 12개의 REST API가 추가되었는지를 확인합니다. 만일 빌드 시 에러가 발생하거나, 원하는 API 목록이 출력되지 않는다면 다음 프롬프트를 사용해서 정상적인 결과값이 나올때까지 수정을 반복해서 이슈를 해결합니다. - -``` -빌드 시 오류가 발생해. 오류를 해결해줘 -``` - -#### Database URL 변경 - -이제 기존 Python에서 사용하던 데이타베이스를 참조하도록 환경을 변경해 봅니다. 해당 파일은 다음 위치에 존재합니다. - -``` -/workspaces/github-copilot-bootcamp-2025/python/sns.db -``` - -Spring Boot 프로젝트의 다음 파일을 오픈해서 파일 주소를 변경합니다. - -* project_root: /workspaces/github-copilot-bootcamp-2025/java/demo -* 파일 명: /src/main/resources/application.properties - -변경할 내용은 다음과 같습니다. - -``` -spring.datasource.url=jdbc:sqlite:sns.db -``` - -> **NOTE**: 만약 Python 앱에서 쓰던 `sns.db`를 그대로 활용하고 싶다면, `python/sns.db` 파일을 `java/demo/sns.db`로 복사합니다. - -다시 앱을 빌드해서 데이타베이스가 제대로 참조되었는지 확인합니다. - -### 백엔드 앱 전환 및 확인 - -#### 확인 - -이제 모든 코드 생성이 완료되었습니다. 마지막으로 Node JS로 작성된 프론트엔드 앱에서 기존 URL과 동일하게 호출할 수 있도록 Spring Boot 앱의 포트를 변경합니다. - -변경 전 [여기](01-python.md#서비스-종료)를 참고하여 Python 앱을 구동 중지합니다. - - -포트 변경을 위한 설정을 변경하기 위해 GitHub Copilot에 다음과 같이 프롬프트를 입력합니다. - -``` -앱 서비스 포트를 8080으로 변경해줘 -``` - -이제 앱을 다시 빌드하고 구동시켜서 다음 URL로 접속이 되는지를 확인합니다. - -``` -https://localhost:8080/swagger-ui.html -``` - -앱이 정상적으로 구동되었으면 Node JS 프론트엔드 앱을 호출하여 앱에 이상이 없는지 확인합니다. - -``` -http://localhost:3000 -``` + If app running fails, analyze the issues and fix them. + ``` + +1. Open a web browser and navigate to `http://localhost:8080`. +1. Click the `[keep]` button of GitHub Copilot to take the changes. --- -축하합니다! **Java 앱 개발** 실습이 끝났습니다. 이제 [STEP 04: .NET 앱 개발](./04-dotnet.md) 단계로 넘어가세요. +OK. You've completed the "Java" step. Let's move onto [STEP 04: .NET Migration from JavaScript](./04-dotnet.md). diff --git a/docs/04-dotnet.md b/docs/04-dotnet.md index 939eb1a..b1bb445 100644 --- a/docs/04-dotnet.md +++ b/docs/04-dotnet.md @@ -73,6 +73,7 @@ Refer to the [README](../README.md) doc for preparation. - Show me the list of .NET projects related to Blazor and ask me to choose. - Generate a Blazor project. - Use the project name of `Contoso.BlazorApp`. + - Update `launchSettings.json` to change the port number of `3030` for HTTP, `43030` for HTTPS. - Create a solution, `ContosoWebApp`, and add the Blazor project into this solution. - Build the Blazor app and verify if the app is built properly. - Run this Blazor app and verify if the app is running properly. @@ -89,7 +90,7 @@ Refer to the [README](../README.md) doc for preparation. ```text Now, we're migrating the existing React-based web app to Blazor web app. Follow the instructions below for the migration. - - The existing React application is located at `complete/javascript`. + - The existing React application is located at `javascript`. - Your working directory is `dotnet/Contoso.BlazorApp`. - Identify all the steps first, which is you're going to do. - Analyze the application structure of the existing React app. diff --git a/docs/custom-instructions/java/copilot-instructions.md b/docs/custom-instructions/java/copilot-instructions.md new file mode 100644 index 0000000..cb85a87 --- /dev/null +++ b/docs/custom-instructions/java/copilot-instructions.md @@ -0,0 +1,92 @@ +# Java Development Rules + +You are a senior Java developer and an expert in Java programming, Spring Boot, Spring Boot CLI, Spring Framework, Maven, Gradle, JUnit, and related Java technologies. + +## Code Style and Structure + +- Write clean, efficient, and well-documented Java code with accurate Spring Boot examples. +- Use Spring Boot best practices and conventions throughout your code. +- Implement RESTful API design patterns when creating web services. +- Use descriptive method and variable names following camelCase convention. +- Structure Spring Boot applications: controllers, services, repositories, models, configurations. + +## Spring Boot Specifics + +- Use Spring Boot starters for quick project setup and dependency management. +- Implement proper use of annotations (e.g., @SpringBootApplication, @RestController, @Service). +- Utilize Spring Boot's auto-configuration features effectively. +- Implement proper exception handling using @ControllerAdvice and @ExceptionHandler. + +## Naming Conventions + +- Use PascalCase for class names (e.g., UserController, OrderService). +- Use camelCase for method and variable names (e.g., findUserById, isOrderValid). +- Use ALL_CAPS for constants (e.g., MAX_RETRY_ATTEMPTS, DEFAULT_PAGE_SIZE). + +## Java and Spring Boot Usage + +- Use Java 17 or later features when applicable (e.g., records, sealed classes, pattern matching). +- Leverage Spring Boot 3.x features and best practices. +- Use Spring Data JPA for database operations when applicable. +- Implement proper validation using Bean Validation (e.g., @Valid, custom validators). + +## Configuration and Properties + +- Use application.properties or application.yml for configuration. +- Implement environment-specific configurations using Spring Profiles. +- Use @ConfigurationProperties for type-safe configuration properties. + +## Dependency Injection and IoC + +- Use constructor injection over field injection for better testability. +- Leverage Spring's IoC container for managing bean lifecycles. + +## Testing + +- Write unit tests using JUnit 5 and Spring Boot Test. +- Use MockMvc for testing web layers. +- Implement integration tests using @SpringBootTest. +- Use @DataJpaTest for repository layer tests. + +## Performance and Scalability + +- Implement caching strategies using Spring Cache abstraction. +- Use async processing with @Async for non-blocking operations. +- Implement proper database indexing and query optimization. + +## Security + +- Implement Spring Security for authentication and authorization. +- Use proper password encoding (e.g., BCrypt). +- Implement CORS configuration when necessary. + +## Logging and Monitoring + +- Use SLF4J with Logback for logging. +- Implement proper log levels (ERROR, WARN, INFO, DEBUG). +- Use Spring Boot Actuator for application monitoring and metrics. + +## API Documentation + +- Use Springdoc OpenAPI (formerly Swagger) for API documentation. + +## Data Access and ORM + +- Use Spring Data JPA for database operations. +- Implement proper entity relationships and cascading. +- Use database migrations with tools like Flyway or Liquibase. + +## Build and Deployment + +- Use either Maven or Gradle for dependency management and build processes. +- Gradle is preferred for new projects due to its flexibility and performance. +- Implement proper profiles for different environments (dev, test, prod). +- Use Docker for containerization if applicable. + +## Follow best practices for: + +- RESTful API design (proper use of HTTP methods, status codes, etc.). +- Microservices architecture (if applicable). +- Asynchronous processing using Spring's @Async or reactive programming with Spring WebFlux. + +Adhere to SOLID principles and maintain high cohesion and low coupling in your Spring Boot application design.