🧠 AI with Java & Spring Boot – Part 1: Getting Started with AI in the Java Ecosystem
Hey devs! 👋
Welcome to the first post in my "AI with Java and Spring" series, where we explore how to harness the power of Artificial Intelligence in the Java ecosystem—using tools you already know and love like Spring Boot.
In this series, we’ll dive into:
- AI concepts applied with Java
- Using external AI APIs like OpenAI, Hugging Face, etc.
- Integrating ML models into Spring Boot services
- And building hands-on applications!
This post sets the foundation and walks you through a handy example: Creating an AI-powered text summarizer with Java, Spring Boot, and OpenAI’s API.
🚀 Why Java + AI?
While Python dominates the AI/ML space, Java is no stranger to the game. In enterprise environments, Java still powers a lot of backend services. Combining AI APIs with your existing Java stack can bring machine learning benefits without reinventing your backend in Python.
🧰 What You’ll Need
- Java 17+
- Spring Boot (3.x)
- Maven or Gradle
- OpenAI API Key (you can sign up at platform.openai.com)
- Basic knowledge of Spring REST
🔧 Step-by-Step: Text Summarizer with OpenAI and Spring Boot
1. Initialize Your Spring Boot Project
Generate a Spring Boot app with:
- Spring Web
- Spring Boot DevTools
- Lombok (optional, but makes life easier)
- Configuration Processor
You can use Spring Initializr or your favorite IDE.
2. Add Dependencies (Maven example)
org.springframework.boot
spring-boot-starter-web
com.fasterxml.jackson.core
jackson-databind
org.springframework.boot
spring-boot-configuration-processor
true
3. Configure API Key in application.yml
openai:
api-key: YOUR_OPENAI_API_KEY
model: gpt-3.5-turbo
4. Create OpenAIService.java
@Service
public class OpenAIService {
@Value("${openai.api-key}")
private String apiKey;
@Value("${openai.model}")
private String model;
private static final String OPENAI_API_URL = "https://api.openai.com/v1/chat/completions";
public String summarizeText(String input) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBearerAuth(apiKey);
Map<String, Object> message = Map.of(
"role", "user",
"content", "Summarize this text: " + input
);
Map<String, Object> request = Map.of(
"model", model,
"messages", List.of(message)
);
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(request, headers);
ResponseEntity<Map> response = restTemplate.postForEntity(OPENAI_API_URL, entity, Map.class);
List<Map<String, Object>> choices = (List<Map<String, Object>>) response.getBody().get("choices");
Map<String, Object> messageData = (Map<String, Object>) choices.get(0).get("message");
return (String) messageData.get("content");
}
}
5. Create Controller: AIController.java
@RestController
@RequestMapping("/api/ai")
public class AIController {
private final OpenAIService openAIService;
public AIController(OpenAIService openAIService) {
this.openAIService = openAIService;
}
@PostMapping("/summarize")
public ResponseEntity<String> summarize(@RequestBody Map<String, String> request) {
String text = request.get("text");
String summary = openAIService.summarizeText(text);
return ResponseEntity.ok(summary);
}
}
6. Test It Out!
You can use Postman or curl
:
curl -X POST http://localhost:8080/api/ai/summarize \
-H "Content-Type: application/json" \
-d '{"text": "OpenAI provides powerful AI tools including GPT-4 and Codex..."}'
🔚 Wrapping Up
And there you go — you just built an AI-powered text summarizer with Spring Boot and OpenAI! 😎
In the next part of this series, we’ll explore:
- Streaming ChatGPT responses
- Building conversational AI bots with Java
- Integrating Hugging Face transformers into Spring
If you liked this post, don’t forget to:
❤️ Like
💬 Comment
📌 Follow for the next episode!
Happy coding!