Spring AI 实战:快速上手指南
作者:微信文章Spring AI 是 Spring 官方推出的 AI 框架,简化了 Java 应用与 AI 模型的集成。本文通过一个实战示例,带你快速上手 Spring AI。
场景:天气查询机器人
我们将构建一个基于 Spring Boot 的 Web 应用,用户输入城市名,AI 返回天气信息。
️ 技术栈
Spring Boot 3.xSpring AIOpenAI APIMavenLombok
项目结构
深色版本spring-ai-weather-bot/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com.example.springai.controller.WeatherController
│ │ │ └── com.example.springai.service.WeatherService
│ │ │ └── com.example.springai.model.WeatherResponse
│ │ ├── resources/
│ │ │ └── application.yml
│ └── test/
├── pom.xml 依赖配置(pom.xml)
xml
深色版本
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>0.8.1</version>
</dependency> 核心代码
1.application.yml
yaml
深色版本
spring:
ai:
openai:
api-key: your_openai_api_key2.WeatherController.java
java
深色版本
@RestController
@RequestMapping("/api/weather")
publicclassWeatherController{
privatefinal WeatherService weatherService;
public WeatherController(WeatherService weatherService) {
this.weatherService = weatherService;
}
@GetMapping("/{city}")
public WeatherResponse getWeather(@PathVariable String city) {
return weatherService.getWeather(city);
}
}3.WeatherService.java
java
深色版本
@Service
publicclassWeatherService{
privatefinal AiClient aiClient;
publicWeatherService(AiClient aiClient){
this.aiClient = aiClient;
}
public WeatherResponse getWeather(String city){
String prompt = String.format("查询 %s 的天气情况", city);
String response = aiClient.generate(prompt);
returnnew WeatherResponse(city, response);
}
}4.WeatherResponse.java
java
深色版本
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WeatherResponse {
privateStringcity;
privateStringforecast;
} UML 类图
plaintext
深色版本
+---------------------+
| WeatherController |
+---------------------+
| +getWeather() |
+---------------------+
|
v
+---------------------+
| WeatherService |
+---------------------+
| +getWeather() |
+---------------------+
|
v
+---------------------+
| AiClient |
+---------------------+
| +generate() |
+---------------------+ 启动项目
bash
深色版本
mvnspring-boot:run
访问:
http://localhost:8080/api/weather/beijing
返回:
json
深色版本
{
"city": "beijing",
"forecast": "晴,气温25°C,微风。"
}✅ 小结
Spring AI 极大简化了 AI 集成流程。可轻松对接 OpenAI、Azure 等平台。适用于聊天机器人、文本生成、数据分析等场景。
参考资料
Spring AI 官方文档OpenAI API 文档
关注我,获取更多 Spring AI 实战案例!
页:
[1]