默认配置
默认情况下,Spring Boot自动配置将使用spring.ai.openai.api-key属性创建一个API key bean:
spring.ai.openai.api-key=your-api-key-here
这种方式能让应用正常启动,但并不是最优雅的解决方案,因为直接在配置文件中明文存储密钥存在泄露风险。
自定义API密钥配置
您可以使用builder模式,使用自己的OpenAiApi实现创建ApiKey的自定义实例:
ApiKey customApiKey = new ApiKey() { @Override public String getValue() { // Custom logic to retrieve API key return "your-api-key-here"; }};OpenAiApi openAiApi = OpenAiApi.builder() .apiKey(customApiKey) .build();// Create a chat model with the custom OpenAiApi instanceOpenAiChatModel chatModel = OpenAiChatModel.builder() .openAiApi(openAiApi) .build();// Build the ChatClient using the custom chat modelChatClient openAiChatClient = ChatClient.builder(chatModel).build();
这在你需要的时候很有用:
从安全密钥存储中检索API密钥
动态获取密钥,支持密钥轮换
实现自定义API密钥选择逻辑
API 密钥的管理不仅仅是配置问题,更是系统安全架构设计的重要组成部分。
Spring AI框架虽然默认要求启动时配置API密钥,但通过合理的扩展和定制,完全可以实现更灵活的密钥管理方案。
开发者应该根据实际业务需求,选择最适合的动态密钥管理方式,既保证应用安全性,又提高部署灵活性。