HomeBlogSpring Boot AI Prompts: Build Production Java APIs…
Programming18 min read · May 10, 2026

Spring Boot AI Prompts: Build Production Java APIs Faster in 2026

By Promptprepare Team · AI Prompt Experts

Complete AI prompt library for Spring Boot developers. Covers REST APIs with Spring WebFlux, Spring Security JWT, Spring Data JPA with Hibernate, Testcontainers integration testing, Kafka event streaming, Docker deployment, and performance tuning.

#Spring Boot#Java#Spring Security#JPA#Kafka#AI Coding Prompts#Backend

Spring Boot in 2026: Java's Enterprise-Grade API Framework

Spring Boot 3.x with Java 21 is a fundamentally different platform from the Spring Boot 2.x that dominates most AI training data. Virtual threads, records, sealed classes, Spring Security's new lambda DSL, and native compilation with GraalVM require modern prompts that explicitly target the new APIs. These prompts produce code that compiles and runs correctly on Spring Boot 3.x — not legacy configurations that require migration.

1. Spring Boot 3 Project Setup

You are a senior Spring Boot 3 architect using Java 21.

Design a production Spring Boot 3.3 application for a multi-tenant SaaS REST API:
- Build: Gradle (Kotlin DSL), not Maven
- Java 21 with virtual threads enabled (spring.threads.virtual.enabled=true)
- Spring Web MVC (not WebFlux — virtual threads provide the throughput we need)
- Spring Data JPA + Hibernate 6 + PostgreSQL
- Spring Security 6 with JWT (stateless)
- Spring Cache + Redis (Lettuce client)
- Spring Actuator for health and metrics
- Kafka for domain events

Deliver:
1. build.gradle.kts with all dependencies and versions
2. Package structure: com.company.app.{domain}/{application,domain,infrastructure,presentation}
3. application.yml for local development, application-prod.yml for production (env var placeholders)
4. Docker Compose for local: PostgreSQL 16, Redis 7, Kafka 3.7
5. The top 3 Spring Boot 3 features you are using and why they matter

2. REST Controller with Validation

You are a Spring Boot 3 REST API expert.

Build a complete TaskController for a project management API:

Endpoints: GET /api/v1/tasks (paginated), GET /api/v1/tasks/{id}, POST /api/v1/tasks, PUT /api/v1/tasks/{id}, DELETE /api/v1/tasks/{id}

Requirements:
- @RestController with @RequestMapping("/api/v1/tasks")
- @Validated on controller class for constraint validation
- DTOs: TaskCreateRequest (record with @Valid constraints), TaskUpdateRequest (record, all fields Optional), TaskResponse (record, mapped from entity)
- Tenant scoping: extract organizationId from JWT (SecurityContextHolder), pass to service
- Response wrapper: ApiResponse<T> record { T data, String requestId, Instant timestamp }
- Error handling: @RestControllerAdvice with handlers for MethodArgumentNotValidException (field errors), EntityNotFoundException (404), AccessDeniedException (403)
- Pagination: return Page<TaskResponse> wrapped in ApiResponse

Use Java 21 records for all DTOs. No Lombok required — use records and canonical constructors.

3. Spring Security JWT Configuration

You are a Spring Security 6 expert.

Configure JWT authentication for a Spring Boot 3 REST API using the SecurityFilterChain approach (NOT WebSecurityConfigurerAdapter):

Security config:
- Stateless session: SessionCreationPolicy.STATELESS
- CORS: allowedOrigins from environment, allowedMethods GET/POST/PUT/DELETE/OPTIONS
- CSRF: disabled (stateless JWT API)
- Public endpoints: /api/v1/auth/**, /actuator/health, /swagger-ui/**
- All other endpoints: authenticated

JWT filter (JwtAuthenticationFilter extends OncePerRequestFilter):
- Extract Bearer token from Authorization header
- Validate with JJWT (io.jsonwebtoken:jjwt-impl)
- Extract claims: userId, organizationId, role
- Set UsernamePasswordAuthenticationToken in SecurityContext

Token service:
- Generate access token (RS256, 15 minutes) — keys loaded from environment as Base64
- Generate refresh token (opaque UUID stored in Redis, 7 days TTL)
- Validate token: check signature, expiry, and not-blacklisted
- Refresh: validate Redis entry, issue new pair, invalidate old refresh token

Method security:
- @EnableMethodSecurity on config class
- Use @PreAuthorize("hasRole('ORG_ADMIN')") on admin endpoints
- Custom permission evaluator: @PreAuthorize("@taskPermissionEvaluator.canEdit(#taskId, authentication)")

Output: SecurityConfig, JwtAuthenticationFilter, JwtTokenService, and PermissionEvaluator.

4. Spring Data JPA Repository with Optimization

You are a Spring Data JPA and Hibernate 6 expert.

Design JPA entities and repositories for a multi-tenant task management system:

Entities (Java 21 — use @Entity with records where possible, standard classes where JPA requires):
- Organization, User, Project, Task, AuditLog
- Auditing: @EnableJpaAuditing, @CreatedDate, @LastModifiedDate, @CreatedBy, @LastModifiedBy
- Soft delete: @SQLRestriction("deleted_at IS NULL") on entities (Hibernate 6 syntax — not @Where)
- Multi-tenant: @Filter for organizationId (Hibernate Filter, activated per request in interceptor)

TaskRepository (JpaRepository + custom):
- findByProjectIdAndStatus(projectId, status, Pageable): @EntityGraph to load assignee
- findOverdueTasks(organizationId, now): @Query JPQL with date comparison
- bulkUpdateStatus(taskIds, status): @Modifying @Query @Transactional — single UPDATE statement
- countByStatusGrouped(organizationId): @Query returning List<StatusCount> projection interface
- findWithFilters(spec, pageable): JpaSpecificationExecutor for dynamic filtering

Performance:
- @QueryHints with COMMENT for DBA query identification
- @BatchSize on collections to prevent N+1 with IN clause batching
- Database indexes: composite indexes declared in @Table(indexes={...})

Output: entity classes, repositories, Hibernate filter configuration, and tenant activation interceptor.

5. Kafka Event Streaming

You are a Spring Kafka expert.

Implement domain event streaming for a Spring Boot application:

Domain events (records):
- TaskCreatedEvent(taskId, title, projectId, organizationId, createdBy, occurredAt)
- TaskStatusChangedEvent(taskId, previousStatus, newStatus, changedBy, occurredAt)
- TaskAssignedEvent(taskId, previousAssignee, newAssignee, occurredAt)

Producer:
- KafkaTemplate<String, Object> with JSON serializer
- Topic naming: app.tasks.events (single topic, event type in header)
- Transactional outbox pattern: save event to outbox table in same DB transaction as entity save
- Outbox relay: @Scheduled task polls outbox table, publishes to Kafka, marks as published

Consumer (notification-service):
- @KafkaListener on tasks.events topic, partitioned by organizationId key
- Idempotency: check event ID in Redis before processing (TTL 24h)
- Error handling: DefaultErrorHandler with exponential backoff (1s, 2s, 4s), dead-letter topic after 3 failures
- Manual acknowledgment: only commit offset after successful processing

Topics configuration: 12 partitions, replication-factor 3 (production), 1 (local Docker)

Output: KafkaConfig, event records, TaskEventPublisher, outbox table + scheduler, TaskEventConsumer.

6. Testcontainers Integration Tests

You are a Spring Boot testing expert using Testcontainers.

Write integration tests for TaskController using real PostgreSQL and Redis:

Test setup:
- @SpringBootTest(webEnvironment = RANDOM_PORT)
- @Testcontainers at class level
- @Container static PostgreSQLContainer (shared across all tests in class for speed)
- @Container static GenericContainer for Redis
- @DynamicPropertySource: inject container URLs into Spring DataSource and Redis config
- TestRestTemplate or WebTestClient for HTTP calls

Test data:
- @Sql(scripts = {"/sql/clean.sql", "/sql/seed-tasks.sql"}) per test method
- Helper: createAuthToken(userId, organizationId, role) — real JWT signed with test key

Tests:
1. GET /api/v1/tasks: 200, correct pagination, only current org's tasks returned
2. POST /api/v1/tasks: 201, task in DB, Kafka event published (EmbeddedKafka)
3. POST with invalid data: 400, field-level error map in response
4. GET /api/v1/tasks/{id}: 404 for different org's task (tenant isolation)
5. DELETE: 204, soft-deleted (deletedAt set), excluded from subsequent GET
6. Concurrent update: two threads update same task → optimistic lock exception → 409

Show: Testcontainers setup class (reusable across test classes), JWT helper, and SQL seed file.

7. Good vs Bad Spring Boot Prompts

Task❌ Bad Prompt✅ Good Prompt
Security"Add JWT auth to Spring Boot""Configure Spring Security 6 JWT for Spring Boot 3 using SecurityFilterChain (not WebSecurityConfigurerAdapter): stateless session, JwtAuthenticationFilter extends OncePerRequestFilter, RS256 validation with JJWT, userId + organizationId + role in claims, @PreAuthorize on methods."
JPA"Query tasks from the database""Write a Spring Data JPA @Query for tasks filtered by organizationId, status, and due_date range with Pageable. Use @EntityGraph to load assignee (prevent N+1). Add @Modifying @Transactional for the bulk status update method. Use Hibernate 6 @SQLRestriction for soft delete filtering."
Testing"Write tests for my API""Write Testcontainers integration tests for TaskController: real PostgreSQL 16 + Redis 7 containers, @Sql seed data per test, real JWT token factory, assert HTTP status + response body + DB state + Kafka event published. Test tenant isolation: org A cannot access org B's tasks."

Generate a custom Spring Boot prompt → Try PromptPrepare free

Found this helpful? Share it.