DEV Community

Cover image for Getting Started with AI in the Java Ecosystem
araf
araf

Posted on • Edited on

Getting Started with AI in the Java Ecosystem

๐Ÿง  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)

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

3. Configure API Key in application.yml

openai:
  api-key: YOUR_OPENAI_API_KEY
  model: gpt-3.5-turbo
Enter fullscreen mode Exit fullscreen mode

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");
    }
}
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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..."}'
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”š 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:

If you liked this post, donโ€™t forget to:
โค๏ธ Like

๐Ÿ’ฌ Comment

๐Ÿ“Œ Follow for the next episode!

Happy coding!

Top comments (0)