ParameterizedTypeReference is a Spring type token that preserves a parameterized Java type when ChatClient passes it to entity(). It prevents generic type information, such as List<String>, from being lost through Java type erasure. section 3.4.2
Returning a list from ChatClient
A top-songs controller can call entity(new ParameterizedTypeReference<List<String>>() {}) and return the result as JSON. The resulting endpoint converts the generated response into a list of song titles. section 3.4.2
Listing 3.6 Controller that returns the top songs for a year
package com.example.topsongs;
import java.util.List;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TopSongsController {
@Value("classpath:/top-songs-prompt.st")
Resource topSongPromptTemplate; #1
private final ChatClient chatClient;
public TopSongsController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
@GetMapping(path = "/topSongs", produces = "application/json")
public List<String> topSongs(@RequestParam("year") String year) {
return chatClient.prompt()
.user(userSpec -> userSpec
.text(topSongPromptTemplate)
.param("year", year))
.call()
.entity(new ParameterizedTypeReference<List<String>>() {}); #2
}
}
The controller listing shows the Spring imports, endpoint declaration, and ParameterizedTypeReference<List<String>> usage in context. section 3.4.2
