我来为您提供几个Java中使用AI生成文档的实战案例。

案例1:使用OpenAI API生成Javadoc注释
import com.theokanning.openai.service.OpenAiService;
import com.theokanning.openai.completion.chat.*;
import java.util.Arrays;
public class AIDocGenerator {
private final OpenAiService service;
public AIDocGenerator(String apiKey) {
this.service = new OpenAiService(apiKey);
}
/**
* 为Java方法生成Javadoc注释
*/
public String generateJavadoc(String methodCode, String className) {
String prompt = String.format(
"为以下Java方法生成专业的Javadoc注释,包含参数说明、返回值说明和异常说明:\n\n方法代码:\n%s\n\n类名:%s",
methodCode, className
);
ChatCompletionRequest request = ChatCompletionRequest.builder()
.model("gpt-3.5-turbo")
.messages(Arrays.asList(
ChatMessage.builder()
.role("system")
.content("你是一位专业的Java文档编写专家")
.build(),
ChatMessage.builder()
.role("user")
.content(prompt)
.build()
))
.maxTokens(500)
.temperature(0.7)
.build();
ChatCompletionResult result = service.createChatCompletion(request);
return result.getChoices().get(0).getMessage().getContent();
}
// 使用示例
public static void main(String[] args) {
AIDocGenerator generator = new AIDocGenerator("your-api-key");
String methodCode = """
public List<User> findUsersByAge(int minAge, int maxAge) {
String sql = "SELECT * FROM users WHERE age BETWEEN ? AND ?";
return jdbcTemplate.query(sql, new Object[]{minAge, maxAge}, userRowMapper);
}
""";
String javadoc = generator.generateJavadoc(methodCode, "UserRepository");
System.out.println(javadoc);
}
}
案例2:使用Hugging Face模型生成API文档
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import java.util.*;
public class HuggingFaceApiDocGenerator {
private static final String API_URL = "https://api-inference.huggingface.co/models/codellama/CodeLlama-7b-hf";
private final String apiToken;
public HuggingFaceApiDocGenerator(String apiToken) {
this.apiToken = apiToken;
}
/**
* 生成REST API接口文档
*/
public String generateApiDocumentation(String controllerCode) {
RestTemplate restTemplate = new RestTemplate();
// 构建请求体
Map<String, Object> requestBody = new HashMap<>();
requestBody.put("inputs", createPrompt(controllerCode));
requestBody.put("parameters", Map.of(
"max_new_tokens", 1000,
"temperature", 0.3,
"do_sample", true
));
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + apiToken);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
// 发送请求
ResponseEntity<String> response = restTemplate.postForEntity(
API_URL, entity, String.class
);
return response.getBody();
}
private String createPrompt(String controllerCode) {
return String.format("""
Generate comprehensive API documentation for this Spring Boot controller:
```java
%s
Include:
1. API endpoint description
2. HTTP method
3. Request parameters
4. Response format
5. Error codes
6. Example request/response
""", controllerCode);
}
## 案例3:使用Local LLM(Ollama)生成项目文档
```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.http.*;
import java.net.URI;
import java.net.http.HttpRequest.BodyPublishers;
public class OllamaDocGenerator {
private static final String OLLAMA_URL = "http://localhost:11434/api/generate";
private final HttpClient client;
private final ObjectMapper mapper;
public OllamaDocGenerator() {
this.client = HttpClient.newHttpClient();
this.mapper = new ObjectMapper();
}
/**
* 生成项目README文档
*/
public String generateReadme(String projectStructure, String projectDescription) {
String prompt = String.format("""
根据以下项目信息生成专业的README.md文档:
项目描述:%s
项目结构:
%s
请包含:
1. 项目简介
2. 技术栈
3. 快速开始指南
4. API文档链接
5. 配置说明
6. 部署说明
""", projectDescription, projectStructure);
return callOllama(prompt);
}
/**
* 生成代码注释的Markdown文档
*/
public String generateCodeDocumentation(String sourceCode, String documentType) {
String prompt = String.format("""
为以下Java代码生成%s格式的文档:
```java
%s
请输出清晰的Markdown格式文档,包含:
- 类说明
- 方法说明
- 参数说明
- 使用示例
""", documentType, sourceCode);
return callOllama(prompt);
}
private String callOllama(String prompt) {
try {
String jsonRequest = mapper.writeValueAsString(Map.of(
"model", "codellama:7b",
"prompt", prompt,
"stream", false
));
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(OLLAMA_URL))
.header("Content-Type", "application/json")
.POST(BodyPublishers.ofString(jsonRequest))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
JsonNode jsonResponse = mapper.readTree(response.body());
return jsonResponse.get("response").asText();
} catch (Exception e) {
throw new RuntimeException("Failed to generate documentation", e);
}
}
## 案例4:批处理文档生成器
```java
import java.io.*;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
public class BatchDocGenerator {
private final AIDocGenerator docGenerator;
private final ExecutorService executor;
public BatchDocGenerator(String apiKey) {
this.docGenerator = new AIDocGenerator(apiKey);
this.executor = Executors.newFixedThreadPool(5);
}
/**
* 批量生成项目文档
*/
public Map<String, String> batchGenerateDocs(String projectPath) throws IOException {
Map<String, String> documentation = new ConcurrentHashMap<>();
List<Path> javaFiles = findJavaFiles(projectPath);
List<CompletableFuture<Void>> futures = javaFiles.stream()
.map(file -> CompletableFuture.runAsync(() -> {
try {
String code = Files.readString(file);
String doc = docGenerator.generateJavadoc(code, file.getFileName().toString());
documentation.put(file.toString(), doc);
System.out.println("Generated doc for: " + file);
} catch (Exception e) {
System.err.println("Failed to process: " + file + " - " + e.getMessage());
}
}, executor))
.collect(Collectors.toList());
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
executor.shutdown();
return documentation;
}
/**
* 保存生成的文档
*/
public void saveDocumentation(Map<String, String> docs, String outputDir) throws IOException {
Path outputPath = Paths.get(outputDir);
Files.createDirectories(outputPath);
for (Map.Entry<String, String> entry : docs.entrySet()) {
String fileName = Paths.get(entry.getKey()).getFileName().toString()
.replace(".java", "_DOC.md");
Path filePath = outputPath.resolve(fileName);
Files.writeString(filePath, entry.getValue());
System.out.println("Saved: " + filePath);
}
}
private List<Path> findJavaFiles(String projectPath) throws IOException {
return Files.walk(Paths.get(projectPath))
.filter(path -> path.toString().endsWith(".java"))
.collect(Collectors.toList());
}
}
案例5:集成到Maven插件
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
@Mojo(name = "generate-ai-docs")
public class AIDocMojo extends AbstractMojo {
@Parameter(property = "apiKey", required = true)
private String apiKey;
@Parameter(property = "sourceDir", defaultValue = "${project.build.sourceDirectory}")
private String sourceDir;
@Parameter(property = "outputDir", defaultValue = "${project.build.directory}/docs")
private String outputDir;
@Override
public void execute() {
getLog().info("Starting AI documentation generation...");
try {
BatchDocGenerator generator = new BatchDocGenerator(apiKey);
Map<String, String> docs = generator.batchGenerateDocs(sourceDir);
generator.saveDocumentation(docs, outputDir);
getLog().info("Generated " + docs.size() + " documentation files");
} catch (Exception e) {
getLog().error("Failed to generate documentation", e);
throw new RuntimeException(e);
}
}
}
使用说明
-
添加依赖(Maven):
<dependency> <groupId>com.theokanning.openai-gpt3-java</groupId> <artifactId>service</artifactId> <version>0.14.0</version> </dependency>
-
配置API密钥:
// 通过环境变量或配置文件设置 System.setProperty("OPENAI_API_KEY", "your-api-key"); -
运行示例:
# 使用Maven插件 mvn com.example:ai-doc-maven-plugin:1.0.0:generate-ai-docs \ -DapiKey=your-api-key
或直接运行Java程序
java AIDocGeneratorExample
这些案例展示了如何利用AI技术自动生成Java项目的各类文档,包括Javadoc注释、API文档、README等,根据实际需求选择合适的方案即可。