Spring Boot’s convention-over-configuration model is genuinely one of the best things to happen to Java productivity — and also the source of the most confusing production bugs I have debugged. Autoconfiguration fires conditions you never set consciously. Security filters block requests for reasons that aren’t logged. Default settings that are fine for development (open-in-view=true, 10-connection HikariCP pool, permissive CORS) quietly create problems at scale.
I built this prompt set specifically for gaps I kept hitting when using AI assistants for Spring Boot work. Generic prompts produce boilerplate that compiles but ignores your Spring Boot version, your actual security requirements, and the performance implications of the defaults chosen. These 10 prompts are engineered around context: they ask you to provide your Spring Boot version, your business rules, and your actual failure scenario, so the AI produces output you can actually commit. Tested against Claude Sonnet 4 and GPT-4o with Spring Boot 3.4 and Spring Security 7.
This post gives you 10 copy-paste AI prompts for Spring Boot development, covering the full lifecycle from initial scaffolding to production hardening and version migration. Each prompt is engineered to give the AI enough context to produce immediately usable, production-quality output.
For background on the Spring ecosystem, see the Java category. For complementary testing prompts, see 10 AI Prompts to Generate JUnit 6 Tests for New Projects.
Getting the Most Out of These Prompts
Two things make the difference between a prompt that produces commit-ready code and one that produces something you spend an hour cleaning up.
Anchor to a specific Spring Boot version. The autoconfiguration conditions, security DSL, and actuator endpoint shapes differ significantly between Spring Boot 2.x, 3.x, and 4.x. A prompt that produces correct 3.2 code will produce deprecated or non-compiling code if the AI defaults to 3.0 assumptions. Every prompt in this post includes a version placeholder — fill it in before using.
Replace all [SQUARE BRACKET] placeholders before pasting. This sounds obvious but the single most common reason AI-generated Spring Boot code fails in practice is that the prompt was used with generic placeholder values — “MyService”, “my-database” — and the AI produces generic placeholder logic to match. Paste your actual class names, your actual endpoint paths, your actual security rules. The AI will produce code that fits your model, not a tutorial example.
Prompt 1: Scaffold a REST Endpoint with Validation
When to use: You are building a new feature and want a complete, production-quality REST endpoint scaffold — controller, service interface, request/response DTOs, and bean validation — generated from a plain-English description of the resource.
Scaffold a Spring Boot 3.x REST endpoint for the following resource.
Resource description:
[DESCRIBE THE RESOURCE, e.g. "A customer order with items, a shipping address, and a status of PENDING, CONFIRMED, SHIPPED, or DELIVERED"]
Generate the following files:
1. Request DTO — a Java record with @NotNull, @NotBlank, @Size, @Email, @Min/@Max annotations as appropriate. Use Jakarta Validation (jakarta.validation.*), not javax.
2. Response DTO — a Java record (no validation annotations needed)
3. Service interface — declare the CRUD method signatures only, no implementation
4. REST Controller — @RestController, @RequestMapping("/api/v1/[resource]"), with:
- POST to create (returns 201 Created with Location header)
- GET /{id} (returns 200 or 404 with ProblemDetail)
- PUT /{id} to update (returns 200 or 404)
- DELETE /{id} (returns 204)
- @Validated on the class, @Valid on @RequestBody parameters
5. Global exception handler stub using @RestControllerAdvice that catches:
- MethodArgumentNotValidException → 400 with field error list
- EntityNotFoundException (or your custom equivalent) → 404 with ProblemDetail (RFC 9457)
Standards to follow:
- Use Java records for DTOs (not classes with getters/setters)
- Return ProblemDetail (Spring 6+) for all error responses
- Include @Operation and @ApiResponse annotations (springdoc-openapi)
- No Lombok
- Show the complete Maven dependency block for spring-boot-starter-web, spring-boot-starter-validation, and springdoc-openapi-starter-webmvc-ui
Prompt 2: Configure Spring Security JWT Authentication
When to use: You need to add stateless JWT-based authentication to a Spring Boot 3.x application and want a correct, production-safe security configuration rather than copy-pasting from outdated StackOverflow answers that still reference the deprecated WebSecurityConfigurerAdapter.
Implement stateless JWT authentication for a Spring Boot 3.x REST API.
Application details:
- Spring Boot version: [3.x]
- Public endpoints (no token required): [e.g. POST /api/v1/auth/login, GET /api/v1/products/**]
- Protected endpoints: [e.g. all /api/v1/** except the above]
- Token expiry: [e.g. 15 minutes for access token, 7 days for refresh token]
Generate the following:
1. SecurityFilterChain bean (component-based, NOT WebSecurityConfigurerAdapter):
- Disable CSRF (stateless API)
- Set session management to STATELESS
- Configure authorizeHttpRequests with the public/protected paths above
- Register a JwtAuthenticationFilter before UsernamePasswordAuthenticationFilter
2. JwtAuthenticationFilter extends OncePerRequestFilter:
- Extract Bearer token from Authorization header
- Validate and parse the token using io.jsonwebtoken (JJWT 0.12+)
- Set SecurityContextHolder authentication on success
- Do NOT throw on missing token — let the security config handle unauthorised access
3. JwtTokenService:
- generateAccessToken(UserDetails user) → signed HS256 JWT with sub, iat, exp claims
- generateRefreshToken(UserDetails user) → longer-lived token
- validateToken(String token, UserDetails user) → boolean
- extractUsername(String token) → String
4. AuthController with POST /api/v1/auth/login that returns access + refresh tokens
5. application.yml entries for jwt.secret and jwt.expiration-ms
Use the JJWT 0.12+ API (Jwts.parser().verifyWith(...)), not the deprecated Jwts.parser().setSigningKey().
Show the complete Maven dependency block.
Prompt 3: Debug Autoconfiguration Failures
When to use: Your Spring Boot application fails to start — or starts but a bean is missing or incorrectly configured — and the error message points at an autoconfiguration class you did not write and do not fully understand.
Diagnose the following Spring Boot autoconfiguration failure and provide a fix.
Full error output (paste the complete startup log from "APPLICATION FAILED TO START"):
[PASTE FULL STACK TRACE HERE]
Spring Boot version: [e.g. 3.2.4]
Relevant starters on the classpath: [e.g. spring-boot-starter-data-jpa, spring-boot-starter-web]
Relevant application.yml / application.properties excerpt:
[PASTE RELEVANT CONFIG HERE]
Diagnosis steps I want you to work through:
1. Which autoconfiguration class is failing, and what @ConditionalOn... condition is not being met?
2. Is a required bean missing from the application context?
3. Is there a classpath conflict (two versions of the same library)?
4. Is there a missing or incorrect property that the autoconfiguration requires?
5. Does the failure only occur in a specific profile?
After diagnosis, provide:
- Root cause in plain English (one sentence)
- The exact fix: missing dependency, missing property, or explicit @Bean definition
- How to verify the fix: which log line or actuator endpoint confirms correct startup
- How to use --debug flag (or spring.autoconfigure.report) to get the full autoconfiguration conditions report for future debugging
Prompt 4: Implement Global Exception Handling
When to use: Your API returns raw stack traces, inconsistent error shapes, or Spring’s default BasicErrorController HTML for JSON clients. You want a single, centralized exception handler that produces RFC 9457 ProblemDetail responses for every error type.
Implement a complete global exception handler for a Spring Boot 3.x REST API using @RestControllerAdvice and RFC 9457 ProblemDetail.
Exception types to handle:
[LIST YOUR EXCEPTIONS, e.g.:
- EntityNotFoundException (custom) → 404
- OrderValidationException (custom, contains a List of field errors) → 422
- DataIntegrityViolationException (Spring) → 409 Conflict
- MethodArgumentNotValidException (Spring) → 400 with field-level detail
- HttpMessageNotReadableException → 400 (malformed JSON body)
- MethodNotAllowedException → 405
- AccessDeniedException (Spring Security) → 403
- Any unhandled Throwable → 500 with sanitised message (no stack trace in body)]
Requirements for each handler:
1. Return ProblemDetail with type URI, title, status, detail, and instance (request path)
2. For validation errors (400/422): include a custom "errors" extension field listing each field + violation message
3. Log WARN for 4xx errors (with request path), ERROR for 5xx errors (with full stack trace)
4. Never leak exception class names or stack traces in the response body
5. Set Content-Type: application/problem+json on all responses
Also generate:
- A custom ApplicationException base class that all domain exceptions extend, carrying an HttpStatus
- An ErrorLoggingFilter (OncePerRequestFilter) that logs the request method + path on every 4xx/5xx
- Integration test using @WebMvcTest that verifies the correct ProblemDetail structure for each exception type
Prompt 5: Write @WebMvcTest for a Controller
When to use: You want fast, focused tests for your REST controller’s HTTP layer — status codes, JSON response structure, validation error responses — without loading the full Spring context.
Generate @WebMvcTest tests for the following Spring Boot 3.x REST controller.
Controller class:
[PASTE YOUR CONTROLLER CLASS HERE]
Request/Response DTO classes:
[PASTE DTO CLASSES HERE]
Service interface (for @MockBean setup):
[PASTE SERVICE INTERFACE HERE]
Test requirements:
- Use @WebMvcTest([ControllerClass].class) with @MockBean for all service dependencies
- Inject MockMvc via @Autowired
- Use @Nested inner classes grouped by endpoint, e.g. "POST /api/v1/orders" and "GET /api/v1/orders/{id}"
- For each endpoint test:
* 200/201 happy path: stub the service, perform request, assert status + jsonPath on key response fields
* 400 validation error: send missing/invalid body, assert status 400 + verify "errors" field in ProblemDetail
* 404 not found: stub service to throw EntityNotFoundException, assert status 404
* 401 unauthorised: omit Authorization header (if endpoint is secured), assert 401
- Use MockMvcRequestBuilders.post/get/put/delete with .contentType(MediaType.APPLICATION_JSON)
- Use Jackson ObjectMapper to serialise request bodies: objectMapper.writeValueAsString(dto)
- Add @DisplayName in English sentences on every @Test method
- Add andDo(print()) to every test (helps with debugging failures in CI)
Also add one integration-level test using @SpringBootTest + TestRestTemplate that verifies the end-to-end happy path persists data.
Prompt 6: Tune application.yml for Production
When to use: You are about to deploy a Spring Boot application to production and want to review your application.yml for dangerous defaults — connection pool settings, timeout values, logging verbosity, and actuator exposure — before anything goes wrong under load.
Audit and improve the following application.yml for production deployment of a Spring Boot 3.x application.
Current application.yml:
[PASTE YOUR application.yml HERE]
Application characteristics:
- Expected concurrent users: [e.g. 500]
- Database: [e.g. PostgreSQL 16 on RDS, max_connections=200]
- Deployment target: [e.g. Kubernetes, 2 pods, 2 CPU / 4GB RAM each]
- External HTTP calls: [e.g. yes, calls 3 downstream REST APIs]
- Caching: [e.g. Redis for session and query cache]
Review and fix each of these areas:
1. HikariCP: maximum-pool-size, minimum-idle, connection-timeout, idle-timeout, max-lifetime — calculate correct pool size for the pod/DB constraints above
2. JPA/Hibernate: show_sql must be false in prod; open-in-view must be false; ddl-auto must be validate or none
3. Spring MVC: server.tomcat.threads.max, server.tomcat.accept-count, server.connection-timeout
4. Actuator: expose only health and info over HTTP; move metrics to a separate management port; disable /actuator/env and /actuator/heapdump in prod
5. Logging: set root level to WARN; keep your own package at INFO; never DEBUG in prod
6. Graceful shutdown: server.shutdown=graceful + spring.lifecycle.timeout-per-shutdown-phase
7. Spring Security headers: add HSTS, X-Frame-Options, X-Content-Type-Options via application config
For each change: show the before/after YAML and explain the production risk of the original setting.
Prompt 7: Add Custom Actuator Health Indicators
When to use: Your Kubernetes readiness and liveness probes hit /actuator/health, but the default indicators only check the database and disk. You want custom indicators for downstream dependencies — external APIs, message brokers, caches — so your pod goes unready before load balancers route traffic to a broken instance.
Implement custom Spring Boot Actuator health indicators for the following downstream dependencies.
Dependencies to monitor:
[LIST YOUR DEPENDENCIES, e.g.:
- PaymentGatewayClient (REST): calls GET /health on the payment gateway API
- KafkaProducer: verifies the Kafka broker connection is alive
- RedisCache: verifies Redis responds to PING
- ExternalReportingService (REST): calls a lightweight ping endpoint]
For each dependency, generate:
1. A class implementing HealthIndicator (or ReactiveHealthIndicator for WebFlux)
2. Health.up() when the dependency responds within timeout
3. Health.down().withDetail("reason", "...").withDetail("responseTime", "...ms") when it fails
4. Health.unknown() when the check itself throws an unexpected exception
5. A timeout of [e.g. 2 seconds] — do NOT block the health check indefinitely
Also generate:
- application.yml entries to:
* Group "readiness" probe: includes database + all custom indicators
* Group "liveness" probe: includes only diskSpace (a failed external API should not kill the pod)
* Set management.endpoint.health.show-details=when-authorized
- A @WebMvcTest for each HealthIndicator that verifies the correct Health status and detail keys
- Kubernetes readinessProbe and livenessProbe YAML snippets pointing to /actuator/health/readiness and /actuator/health/liveness respectively
Prompt 8: Configure CORS and Request Filtering
When to use: Your frontend is hitting CORS errors, or you need to add request ID tracing, IP-based rate limiting, or request logging across all endpoints without duplicating code in every controller.
Configure CORS and request-level cross-cutting concerns for a Spring Boot 3.x REST API.
CORS requirements:
- Allowed origins: [e.g. https://app.example.com, https://staging.example.com — NOT "*" in production]
- Allowed methods: GET, POST, PUT, DELETE, OPTIONS
- Allowed headers: Authorization, Content-Type, X-Request-ID
- Exposed headers: X-Request-ID, X-Response-Time
- Max age: 3600 seconds
- Allow credentials: [true/false]
Cross-cutting filter requirements:
1. RequestIdFilter (OncePerRequestFilter):
- Read X-Request-ID from incoming header or generate a UUID if missing
- Store in MDC (org.slf4j.MDC) as "requestId"
- Add X-Request-ID to the response header
- Clear MDC after the request completes (in finally block)
2. ResponseTimeFilter (OncePerRequestFilter):
- Record start time on request entry
- Add X-Response-Time header (value in milliseconds) before response is committed
3. RequestLoggingFilter:
- Log method + URI + query string + X-Request-ID at INFO on every request
- Log status code + response time at INFO on every response
- Do NOT log request/response bodies (potential PII)
Generate:
- A CorsConfigurationSource @Bean implementing the requirements above (not @CrossOrigin on controllers)
- The three OncePerRequestFilter implementations
- A FilterRegistrationBean for each filter with explicit ordering: RequestId(1) → ResponseTime(2) → Logging(3)
- logback-spring.xml snippet that includes %X{requestId} in the log pattern for MDC propagation
Prompt 9: Implement Spring Cache with @Cacheable
When to use: You have a service method with an expensive computation or slow database query that is called frequently with the same inputs. You want to add Spring’s declarative caching with a Redis backend, correct eviction strategy, and a cache-aside pattern that handles cache failures gracefully.
Add Spring Boot 3.x declarative caching with Redis to the following service class.
Service class to cache:
[PASTE YOUR SERVICE CLASS HERE]
Cache requirements:
- Backend: Redis (via spring-boot-starter-data-redis)
- Cache name: [e.g. "products", "user-profiles"]
- TTL: [e.g. products: 10 minutes, user-profiles: 1 hour]
- Cache key strategy: [e.g. use the method's first parameter (the ID) as the cache key]
- Null caching: [true/false — whether to cache null returns to prevent cache stampede]
Generate:
1. RedisCacheConfiguration @Bean:
- Configure TTL per cache name using RedisCacheManagerBuilderCustomizer
- Use GenericJackson2JsonRedisSerializer (not Java serialization)
- Set key prefix to "[cacheName]::" to avoid collisions in shared Redis
2. Apply @Cacheable to read methods, @CacheEvict to write/delete methods, @CachePut to update methods
- Use SpEL key expressions where the key is a composite of multiple parameters: key="#dto.userId + ':' + #dto.type"
3. CacheFallbackAspect (@Around) that:
- Catches Redis connectivity exceptions during cache reads
- Logs a WARN and falls through to the database (cache-aside degraded mode)
- Does NOT swallow exceptions from the underlying service method
4. A @SpringBootTest integration test that:
- Verifies the service is only called ONCE when the method is called twice with the same key (uses verify(service, times(1)))
- Verifies the cache is evicted after the delete method is called
5. application.yml Redis and cache configuration
Prompt 10: Migrate from Spring Boot 2.x to 3.x
When to use: You are upgrading a production Spring Boot 2.x application to 3.x and need a systematic checklist of breaking changes — namespace migrations, security filter chain rewrites, and dependency updates — before you touch a single line of code.
Audit and migrate the following Spring Boot 2.x configuration to Spring Boot 3.x.
Current Spring Boot version: [2.x]
Target Spring Boot version: [3.2 or 3.3]
Files to migrate:
[PASTE pom.xml AND KEY CONFIGURATION CLASSES HERE — SecurityConfig, WebMvcConfig, DataSourceConfig, etc.]
Migration checklist to apply:
1. Namespace migration: javax.* → jakarta.*
- Find every javax.servlet, javax.validation, javax.persistence import
- Replace with jakarta.servlet, jakarta.validation, jakarta.persistence
2. Spring Security migration:
- Remove all WebSecurityConfigurerAdapter subclasses
- Rewrite as @Bean SecurityFilterChain methods
- Replace antMatchers() → requestMatchers()
- Replace HttpSecurity.authorizeRequests() → authorizeHttpRequests()
3. Spring Data changes:
- Replace deprecated repository methods (findById vs findOne)
- Update any spring.jpa.properties.hibernate.dialect (many dialects auto-detected in Hibernate 6)
4. Actuator changes:
- management.metrics.* properties moved to management.prometheus.*, management.otlp.*
5. Dependency updates:
- Identify dependencies that need major version bumps for Java 17/Jakarta EE 10 compatibility
- Flag any dependencies that have no Jakarta EE 10 compatible release yet
Output format:
- For each breaking change: file name, line number, before snippet, after snippet, explanation
- A prioritised list: BLOCKER (won't compile) / HIGH (runtime failure) / LOW (deprecated warning)
- pom.xml with all version bumps applied
- Estimated migration effort in hours for a codebase of [N] classes
Tips for Getting Better Spring Boot Results
- Always specify your Spring Boot version. The security configuration, autoconfiguration hooks, and default property keys differ significantly between 2.7.x, 3.1.x, and 3.3.x. A prompt without a version will get you code that may not compile.
- Paste your existing config. For Prompts 3, 6, and 10, the AI produces dramatically better output when you include the actual files. Generic descriptions produce generic fixes.
- Run the autoconfiguration report first. Add
--debugto your JVM args (orspring.autoconfigure.report=truein newer versions) before using Prompt 3. Paste the relevant sections of the report into the prompt for a precise diagnosis. - Review security configuration carefully. AI-generated Spring Security code is usually structurally correct but may miss application-specific requirements — custom UserDetailsService, method-level security, or CSRF exemptions for specific paths. Always review with your threat model in mind.
Frequently Asked Questions (FAQs)
Q1: Can I use these prompts with GitHub Copilot’s inline chat?
Yes, but longer prompts (5, 7, 8) work better in standalone chat (Claude.ai, ChatGPT) where you can paste a full class. Copilot inline chat is better for Prompts 1 and 4 where it has access to your project’s existing class names and imports and can produce more consistent, project-aware output.
Q2: These prompts target Spring Boot 3.x. Do they work for 2.7.x?
Add “Spring Boot 2.7.x, Java 11, javax namespace (not jakarta)” to the prompt and the AI will adjust the generated code. The primary differences are the Security configuration pattern (Prompts 2, 5) and the Actuator property names (Prompt 6). Prompt 10 is specifically a 2.x→3.x migration guide and should not be modified.
Q3: How do I handle secrets (JWT secret, Redis password) in the generated configs?
The prompts generate application.yml entries with placeholder values. In production, inject secrets via environment variables using Spring’s ${ENV_VAR_NAME} syntax, or use Spring Cloud Config / AWS Secrets Manager / HashiCorp Vault. Never commit a real secret to a application.yml in source control. Add the following sentence to any prompt that generates config: “Use ${ENV_VAR:defaultValue} notation for all secret values.”
Q4: Why does the generated security config sometimes block all requests?
The most common cause is a missing .permitAll() on public endpoints, or Spring Security’s default deny-all behaviour when a SecurityFilterChain bean is present without explicit rules. Add this to Prompt 2: “Verify that the generated SecurityFilterChain explicitly permits all public endpoints BEFORE the authenticated catch-all rule. Show the requestMatchers in order with a comment explaining why each is placed where it is.”
See Also
- 10 AI Prompts to Generate JUnit 6 Tests for New Projects
- 10 AI Prompts to Debug and Fix JUnit 6 Test Failures
- AI Prompts Playbook: Upgrading Java 8 → 11 → 17 → 21 → 25
- Virtual Threads vs Platform Threads — Benchmarks and Code
Conclusion
These 10 prompts cover the full Spring Boot development lifecycle: scaffolding a complete REST endpoint, securing it with JWT, handling errors uniformly, writing focused slice tests, hardening the configuration for production, instrumenting health checks, adding cross-cutting filters, integrating caching with graceful degradation, and navigating the 2.x to 3.x migration. Copy them, fill in the placeholders, and use the AI output as a strong first draft — one you review against your own security model and production constraints before shipping.