Spring AI with Anthropic Claude — Claude 4 Integration in Spring Boot
Anthropic's Claude models are known for their strong reasoning, long context windows, and careful instruction following — making them excellent for tasks like document analysis, code review, and complex multi-step reasoning. Spring AI provides a dedicated Anthropic starter with full support for Claude's extended thinking, streaming, and vision capabilities.
Maven Dependency
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-anthropic-spring-boot-starter</artifactId>
</dependency>
application.properties
spring.ai.anthropic.api-key=${ANTHROPIC_API_KEY}
spring.ai.anthropic.chat.options.model=claude-sonnet-4-5
spring.ai.anthropic.chat.options.temperature=0.7
spring.ai.anthropic.chat.options.max-tokens=4096
Available models: claude-opus-4-5, claude-sonnet-4-5, claude-haiku-4-5
Basic Chat Service — Same Code as OpenAI
@Service
public class ClaudeService {
private final ChatClient chatClient;
public ClaudeService(ChatClient.Builder builder) {
this.chatClient = builder
.defaultSystem("""
You are an expert Java architect helping developers write better code.
Provide precise, production-quality answers with complete examples.
""")
.build();
}
public String ask(String question) {
return chatClient.prompt()
.user(question)
.call()
.content();
}
public String analyzeCode(String code) {
return chatClient.prompt()
.user("Analyze this Java code for correctness, performance, and design:\n\n" + code)
.call()
.content();
}
}
Long Document Analysis — Claude's 200k Context Window
@Service
public class DocumentAnalysisService {
private final ChatClient chatClient;
public DocumentAnalysisService(ChatClient.Builder builder) {
// Claude Opus handles up to 200,000 tokens — roughly 500 pages of text
this.chatClient = builder
.defaultOptions(AnthropicChatOptions.builder()
.model("claude-opus-4-5")
.maxTokens(8192)
.build())
.build();
}
public String analyzeDocument(String documentContent, String task) {
return chatClient.prompt()
.system("You are a technical document analyst. Be thorough and structured.")
.user("""
Task: {task}
Document:
{document}
""".replace("{task}", task).replace("{document}", documentContent))
.call()
.content();
}
public String compareDocs(String doc1, String doc2) {
return chatClient.prompt()
.user("""
Compare these two technical specifications and identify:
1. Features in doc1 but not in doc2
2. Features in doc2 but not in doc1
3. Contradictions between the docs
Document 1:
%s
Document 2:
%s
""".formatted(doc1, doc2))
.call()
.content();
}
}
Claude Extended Thinking (Deep Reasoning)
@Service
public class ClaudeThinkingService {
private final ChatClient chatClient;
public ClaudeThinkingService(ChatClient.Builder builder) {
this.chatClient = builder
.defaultOptions(AnthropicChatOptions.builder()
.model("claude-opus-4-5")
.thinking(AnthropicApi.ThinkingType.ENABLED, 5000) // 5000 thinking tokens budget
.maxTokens(16000)
.build())
.build();
}
public String solveComplex(String problem) {
// Claude will "think" internally before responding
// The thinking tokens are used for chain-of-thought reasoning
// but only the final answer is returned in the response
return chatClient.prompt()
.user(problem)
.call()
.content();
}
}
Claude with Tool Calling
@Component
public class ArchitectureTools {
@Tool(description = "Check if a Spring Boot dependency is compatible with the given Spring Boot version.")
public String checkCompatibility(String dependency, String springBootVersion) {
// Call Maven Central API or maintain a compatibility matrix
Map<String, String> matrix = Map.of(
"spring-ai+3.3", "Compatible — Spring AI 1.0 supports Spring Boot 3.2+",
"spring-ai+3.1", "Incompatible — Spring AI 1.0 requires Spring Boot 3.2+",
"spring-security+3.3", "Compatible — Spring Security 6.x is the default"
);
return matrix.getOrDefault(dependency + "+" + springBootVersion,
"Compatibility data not available for this combination.");
}
@Tool(description = "Get recommended Spring Boot starter for a specific use case.")
public String getStarter(String useCase) {
return switch (useCase.toLowerCase()) {
case "rest api" -> "spring-boot-starter-web";
case "database" -> "spring-boot-starter-data-jpa";
case "security" -> "spring-boot-starter-security";
case "messaging" -> "spring-boot-starter-amqp";
case "caching" -> "spring-boot-starter-data-redis";
case "ai" -> "spring-ai-openai-spring-boot-starter or spring-ai-anthropic-spring-boot-starter";
default -> "Use https://start.spring.io to find the right starter for: " + useCase;
};
}
}
@Service
public class ClaudeArchitectService {
private final ChatClient chatClient;
public ClaudeArchitectService(ChatClient.Builder builder, ArchitectureTools tools) {
this.chatClient = builder
.defaultSystem("""
You are a Spring Boot architect. Help design and validate
Spring Boot application architectures. Use tools to verify
compatibility and find the right starters.
""")
.defaultTools(tools)
.build();
}
public String design(String requirements) {
return chatClient.prompt().user(requirements).call().content();
}
}
Output
design("I need to build a REST API with PostgreSQL, JWT security, and AI chat features using Spring Boot 3.3")
I'll design your Spring Boot 3.3 application architecture:
**Required Starters:**
- spring-boot-starter-web (REST API)
- spring-boot-starter-data-jpa (PostgreSQL)
- spring-boot-starter-security (JWT)
- spring-ai-anthropic-spring-boot-starter (AI chat)
- postgresql (JDBC driver)
**Compatibility check:** All components are compatible with Spring Boot 3.3 ✓
**Recommended Architecture:**
[controller → service → repository layers with JWT filter chain]
[AI integration as a separate service layer...]
Key Points
- Claude's 200k context window is ideal for analyzing entire codebases or large documents in a single call
- Extended thinking gives Claude more tokens to reason internally — use it for complex architecture decisions and multi-step analysis
- Claude follows complex instructions more precisely than many models — multi-part prompts with numbered requirements work well
- All Spring AI features (tools, memory, advisors, structured output) work identically with Claude and OpenAI
- Use
claude-haiku-4-5for fast, cheap classification and extraction tasks;claude-opus-4-5for deep analysis
Comments