Developing with Java and Spring Boot Using Amazon CodeWhisperer

Introduction

Writing enterprise-grade Java applications with Spring Boot involves repetitive boilerplate, intricate configuration, and security-conscious coding. Amazon CodeWhisperer (now part of Amazon Q Developer) is an AI-powered coding assistant designed to accelerate development by generating contextually relevant code suggestions, performing security scans, and helping with unit tests — all while keeping your intellectual property and data privacy front and center.

This post walks through using CodeWhisperer in a Spring Boot project: from IDE setup and auth to generating controllers, repositories, DTOs, and tests, plus security scanning best practices.

What Is Amazon CodeWhisperer?

Amazon CodeWhisperer is an AI pair-programmer from AWS. In late 2023, it was integrated into Amazon Q Developer, a unified GenAI experience for AWS builders that combines code generation, transformation, troubleshooting, and security features. For IDE-based Java development, the core features remain:

  • Real-time code suggestions — single-line completions and full-function generations
  • Security scan — detect vulnerabilities (OWASP Top 10) with remediation guidance
  • Unit test generation — create JUnit tests with coverage for existing code
  • Reference tracking — recommends open-source attribution where applicable

It's distinct from GitHub Copilot in that it offers a free tier and is tightly integrated with AWS services, making it attractive for AWS-centric teams building microservices on Spring Boot.

Prerequisites

  • An AWS account (Builder ID free tier or IAM Identity Center for Professional tier)
  • Java 17+ and Spring Boot 3.x project
  • IntelliJ IDEA (2023.3+) or VS Code (1.80+) — CodeWhisperer plugins available for both
  • AWS Toolkit extension installed in your IDE

Step 1: Install and Authenticate the AWS Toolkit

IntelliJ IDEA Setup

  1. Open Settings → Plugins → Marketplace, search for "AWS Toolkit", and install.
  2. Restart the IDE. Open the AWS tool window (right sidebar).
  3. Under CodeWhisperer → Connect, choose either:
    • AWS Builder ID (Free) — personal account, no credit card, ideal for individual exploration.
    • AWS IAM Identity Center (Pro) — organization-managed, includes admin dashboards, SSO, and policy controls.
  4. Complete the browser-based SSO flow; the IDE stores credentials via its secure credential manager.

VS Code Setup

# Install the AWS Toolkit extension
code --install-extension amazonwebservices.aws-toolkit-vscode

# Then open the Command Palette (Ctrl+Shift+P)
# → "AWS: Connect to AWS Builder ID" OR "AWS: Use IAM Identity Center"
// Full command palette options:
"AWS: Connect to AWS"
"CodeWhisperer: Start Security Scan"
"CodeWhisper>er: Generate Unit Tests"
Enterprise tip: IAM Identity Center (Pro tier) enables SSO for your whole org, granular code-scan dashboard in the Q Developer console, and auto-onboarding for audits. Builder ID (Free) supports 50 security scans and 500 code suggestions per month.

Step 2: Configure CodeWhisperer for Spring Boot Java Context

CodeWhisperer learns from open files, recently edited code, and the project's dependency graph (parsed from pom.xml). To get the best Spring Boot suggestions:

Maven Dependency Graph Is Key

Make sure your pom.xml includes the Spring Boot starters you actually use. CodeWhisperer's context engine reads these to infer correct annotations and bean wiring:

<dependencies>
  <!-- Include what you're using — the AI uses these for suggestions -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</artifactId>
    <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
  <!-- Test dependency — Critical for unit test generation -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

Enable Auto-Suggestions (Optional)

{
  // VS Code settings.json — customize UX
  "aws.codeWhisperer.showSuggestionsInline": true,
  "aws.codeWhisperer.inlineCompletionDelayMs": 50,
  "aws.codeWhisperer.includeSuggestionsConfigFile": true
}

Step 3: Generating a Spring Boot REST Controller

Start with a comment describing the endpoint. CodeWhisperer generates the full controller in many cases:

// Controller: Exposed /api/products endpoints.
// GET /api/products/{sku} → returns ProductDto
// POST /api/products → accepts ProductCreateRequest, returns 201 with Location header
// DELETE /api/products/{sku} → returns 204
// Use ResponseEntity<> and @Valid for request validation
@RestController
@RequestMapping("/api/products")
public class ProductController {

Tab Tab to accept; CodeWhisperer completes the class with @GetMapping, @PostMapping, @DeleteMapping, and proper ResponseEntity patterns matching Spring Web conventions.

Refining Suggestions (the "//"-driven workflow)

  • Single comment → inline completion
  • Multiple comments with HTTP verbs → full class scaffold
  • Blank line + artifacts in other files (e.g., ProductDto, ProductService) → code that references those exact types if they already exist

Step 4: Repository Layer (Spring Data JPA) + DTOs

Use a comment to trigger repository interface generation, including derived query methods CodeWhisperer knows from Spring Data JPA conventions:

// Repository: Spring Data JPA interface for ProductEntity
// Derived queries: findBySku (unique), findByCategoryAndActiveTrue
// Add @EntityScan and auditing? No — just the Repository interface
public interface ProductRepository extends JpaRepository<ProductEntity, Long> {

For DTOs, it correctly generates records or POJOs with validation annotations since spring-boot-starter-validation is on the classpath:

// DTO: ProductCreateRequest with fields name, category, price (BigDecimal)
// name: @NotBlank, @Size(max=100)
// price: @NotNull, @DecimalMin("0.01")
// category: @NotBlank
// Use Java record for immutability

Step 5: Generating Unit Tests with JUnit 5 + Mockito

Right-click the controller class → "CodeWhisperer: Generate Unit Tests" (or run via Command Palette). Result uses @WebMvcTest, @MockBean, and MockMvc:

@WebMvcTest(ProductController.class)
class ProductControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private ProductService productService;

    @Test
    @DisplayName("GET /api/products/{sku} returns 200 and product body")
    void getProductBySku_success() throws Exception {
        // Mock the service
        ProductDto dto = new ProductDto(1L, "p-001", "Widget", "Gadgets", new BigDecimal("19.99"));
        when(productService.getBySku("p-001")).thenReturn(dto);

        // Act & Assert
        mockMvc.perform(get("/api/products/{sku}", "p-001")
                .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("Widget"));
    }

    @Test
    @DisplayName("GET /api/products/{sku} returns 404 when not found")
    void getProductBySku_notFound() throws Exception {
        // TODO: Implement stubbing + assert 404
    }
}
Implementation-status: When you click "Generate", CodeWhisperer analyzes existing code, creates tests for each public method, and inserts @Test stubs with descriptive names. It does NOT execute tests — you run them. For professional tier, it reports test coverage against your codebase.

Step 6: Security Scan (Find & Fix AWS-Concern Vulnerabilities)

Spring Boot's common security footguns are well-known to CodeWhisperer. Run a scan via Command Palette → "CodeWhisperer: Start Security Scan":

Detected Pattern Example Flagged Code Suggested Fix
CWE-798 (Hardcoded Credentials) jdbc.url = "jdbc:mysql://...:password" Use environment variables or AWS Secrets Manager
CWE-327 (Weak Crypto) new SecretKeySpec(key.getBytes(), "AES") Use KeyGenerator with SecureRandom
CWE-89 (SQL Injection) entityManager.createQuery("FROM Product WHERE name = '" + name + "'") Use @Query with :name parameter binding
CWE-22 (Path Traversal) Paths.get(baseDir, userInput) Use Spring's PathUtils + sanitize + whitelist characters
CWE-502 (Deserialization) new ObjectInputStream(...).readObject() Avoid Java native serialization; use Jackson DTOs

Review findings in the AWS Q / CodeWhisperer panel. Fix inline with suggested diff, then commit.

Best Practices & Realistic Workflow Tips

PracticeWhy
Write comments first, then accept codeDrives the generation scope; better than mashing Tab on blank space
Verify every acceptance with testsAI code still has logic bugs; run your Spring context + unit tests
Use IAM Identity Center for orgsAccess control, SSO, and security-scan governance (Pro tier)
Run Security Scan in CI/CD (Pro)Catch vulns before merge; export SARIF report to SonarQube/GitHub Actions
Tag generated code for reviewConfig in Q console: flag auto-generated blocks in PR diffs
Keep Maven dependencies currentCodeWhisperer's context quality improves with accurate classpath metadata
Don't blindly accept test stubsAssertions are templates — add edge cases, timeouts, and mock verification

Limits & When Not to Use It

  • Business logic complexity: CodeWhisperer excels at boilerplate, not your domain's core policies.
  • Nested transaction boundaries: Manual @Transactional design is still better done by humans.
  • Proprietary/corner-case APIs: If your internal Libraries aren't in public code, suggestions may hallucinate signatures. Use reference files + comments.
  • Free tier (Builder ID) limits: 50 security scans / 500 suggestions per month — fine for hobbyists, not for CI pipelines.
  • Latency on large files: In huge controllers, suggestion speed may lag; break into smaller classes (which Spring best practice already recommends).

Conclusion

Amazon CodeWhisperer (via AWS Q Developer) accelerates Spring Boot work by generating precise controller/repository/test scaffolding based on your project's real dependency graph, while its security scanner flags common Java vulnerabilities before they reach production. It's a practical force-multiplier — but treat its output as a draft, not authority. Pair it with code reviews, unit tests, and security scans in your pipeline for engineering-grade results.

Happy coding! Check back soon for our companion post: "Enforcing CodeWhisperer Security Scans in GitHub Actions + SonarQube for Spring Boot CI/CD."

Comments