How to Use GitHub Copilot With Spring Boot REST Controller Generation
🔍 WiseChecker

How to Use GitHub Copilot With Spring Boot REST Controller Generation

You want to generate a Spring Boot REST controller quickly using GitHub Copilot. Writing CRUD endpoints, request mappings, and response entities manually is repetitive and error-prone. Copilot can autocomplete entire controller classes based on your model and service layers. This article explains how to set up Copilot in your IDE, write effective prompts, and generate complete REST controllers for Spring Boot projects.

Key Takeaways: Generating Spring Boot REST Controllers with GitHub Copilot

  • Ctrl+Enter (Windows/Linux) or Cmd+Enter (Mac): Opens the Copilot suggestions panel to browse multiple completion options.
  • Tab to accept a suggestion: Inserts the generated code inline after Copilot displays a ghost text suggestion.
  • Write a clear class comment or method signature first: Copilot uses that context to generate relevant controller logic, endpoints, and annotations.

ADVERTISEMENT

How GitHub Copilot Generates Spring Boot REST Controllers

GitHub Copilot is an AI pair programmer that suggests code as you type. It understands Spring Boot conventions such as @RestController, @RequestMapping, @GetMapping, and @PostMapping. When you provide a model class like Product and a service class like ProductService, Copilot can generate the controller methods that map HTTP requests to service calls. The quality of the generated code depends on the context you give it. Writing a descriptive class comment or a method signature is the most reliable way to get a useful suggestion.

Prerequisites

You need these items before using Copilot for controller generation:

  • Visual Studio Code, IntelliJ IDEA, or another supported IDE with the GitHub Copilot extension installed and activated
  • A Spring Boot project with Maven or Gradle build files that include the spring-boot-starter-web dependency
  • A model class (entity) and a service class already written in the project
  • An active GitHub Copilot subscription (individual, business, or enterprise plan)

Steps to Generate a Spring Boot REST Controller with Copilot

  1. Open the controller package and create a new Java class
    In your IDE, navigate to the controller package under src/main/java. Right-click the package and select New > Java Class. Name it after your entity, for example ProductController. Press Enter to create the empty file.
  2. Write a class comment that describes the controller purpose
    At the top of the file, type a comment such as // REST controller for Product entity with CRUD endpoints. This comment gives Copilot a clear intent. After typing the comment, press Enter to move to the next line.
  3. Add the @RestController annotation manually
    Type @RestController on the line after the comment. Then type @RequestMapping("/api/products") on the next line. These annotations tell Copilot you are building a REST controller and provide the base URL path.
  4. Declare the class and inject the service dependency
    Type public class ProductController { and press Enter. On the next line, type private final ProductService productService;. Then type a constructor that takes ProductService as a parameter. Copilot may suggest the constructor automatically. Press Tab to accept it.
  5. Generate the first GET endpoint by typing the method signature
    Type public ResponseEntity> getAllProducts() and press Enter. Copilot will suggest the method body including @GetMapping, the call to productService.findAll(), and the return statement. Press Tab to accept the suggestion.
  6. Generate the GET by ID endpoint
    On the next line, type public ResponseEntity getProductById(@PathVariable Long id). Copilot will suggest the method with @GetMapping("/{id}") and the service call. Accept it with Tab.
  7. Generate the POST endpoint for creating a resource
    Type public ResponseEntity createProduct(@RequestBody Product product). Copilot will suggest @PostMapping and the service call for saving. Accept the suggestion.
  8. Generate the PUT endpoint for updating a resource
    Type public ResponseEntity updateProduct(@PathVariable Long id, @RequestBody Product product). Copilot will suggest @PutMapping("/{id}") and the update logic. Accept it.
  9. Generate the DELETE endpoint
    Type public ResponseEntity deleteProduct(@PathVariable Long id). Copilot will suggest @DeleteMapping("/{id}") and the service call for deletion. Accept the suggestion.
  10. Review and edit the generated code
    Check each method for correct HTTP status codes. Copilot may use ResponseEntity.ok() by default. Change to ResponseEntity.status(HttpStatus.CREATED) for POST or ResponseEntity.noContent().build() for DELETE if needed. Add @Valid annotations on @RequestBody parameters for validation.

ADVERTISEMENT

Common Mistakes and Limitations When Using Copilot for Controllers

Copilot generates code that does not compile because of missing imports

Copilot often omits import statements for ResponseEntity, List, or PathVariable. After accepting a suggestion, use the IDE quick-fix feature. In VS Code, hover over the red underline and press Ctrl+. to add the missing import. In IntelliJ, press Alt+Enter on the error.

Copilot suggests methods that call nonexistent service methods

If your service class does not have a method named findAll() or save(), the generated controller will not compile. Before generating the controller, ensure your service class contains the methods you expect. Alternatively, you can accept the suggestion and later implement the missing service methods.

Copilot repeats the same endpoint pattern for every entity

When you generate controllers for multiple entities, Copilot may produce identical method structures. This is acceptable for standard CRUD but can lead to duplicate code. To avoid this, consider creating a generic base controller class and extending it for each entity. Copilot can help generate the base class if you write a comment like // Generic CRUD controller with common methods.

Copilot does not generate custom query endpoints automatically

Copilot works best with standard CRUD patterns. If you need a custom endpoint like /api/products/search?name=, you must write the method signature manually. For example, type public ResponseEntity> searchProducts(@RequestParam String name). Copilot will then suggest the implementation based on the parameter name and return type.

GitHub Copilot Suggestions vs Manual Coding for Spring Boot Controllers

Item Copilot-Generated Manually Written
Setup time Under 2 minutes for a full controller with 5 endpoints 5-10 minutes for the same controller
Annotation accuracy Correct for standard CRUD; may miss @Valid or @ResponseStatus Full control over every annotation
Error handling Basic ResponseEntity.ok() only Can include custom exception handlers and status codes
Consistency across controllers May vary if context differs Uniform structure when using a template
Learning curve Low; requires only typing method signatures Requires knowledge of Spring Boot annotations and patterns

Copilot is best for generating the initial structure of a REST controller. You still need to review and customize the output for production use. Combine Copilot with manual edits for error handling, validation, and logging.

Using Copilot to Generate Service and Repository Layers

Copilot can also generate service and repository layers, which improves the accuracy of controller suggestions. To generate a service class, create a new Java file named ProductService. Write a comment like // Service layer for Product entity with CRUD operations. Then type public class ProductService {. Copilot will suggest methods that call a repository. For the repository, create an interface named ProductRepository that extends JpaRepository. Copilot will suggest the interface declaration and common query methods. After these layers exist, the controller generation becomes more reliable because Copilot uses the actual method signatures from your service.

If Copilot Stops Suggesting Code During Controller Generation

Sometimes Copilot stops showing suggestions. This can happen when the file context is too short or the comment is vague. To restart suggestions, delete the last line and retype it. Alternatively, close the file and reopen it. If the issue persists, check that the GitHub Copilot extension is activated and that you are signed in with your GitHub account. In VS Code, look at the bottom status bar for the Copilot icon. If it shows a crossed-out circle, click it and select Sign In.

You can now generate a complete Spring Boot REST controller with CRUD endpoints using GitHub Copilot. Start by writing a clear class comment and method signatures for each endpoint. After accepting the suggestions, add missing imports and customize error handling. For more complex projects, generate the service and repository layers first to improve the quality of controller suggestions. Try using Copilot to generate a DTO conversion method inside the controller by typing private ProductDTO convertToDTO(Product product) and pressing Enter.

ADVERTISEMENT