liveBook · Manning

ParameterizedTypeReference

As explained in Spring AI in Action

ParameterizedTypeReference is a Spring type token that preserves generic type information when passing a parameterized Java type at runtime.

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

How Spring AI in Action covers it

How deep it goes
Explains generic type preservation and demonstrates a controller call, but does not detail the type-token implementation.
Examples
Uses a top-songs endpoint that converts an LLM response into List<String> containing ten song titles.
What it assumes
Assumes Java generics and ChatClient usage while demonstrating the type-erasure problem through a concrete endpoint.
What you can do after
Apply it via ChatClient to obtain parameterized list responses from generated output.
How it connects
Connects Java generics and type erasure with Spring AI ChatClient response conversion.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring AI in Action. The section links point to the parts of the book it draws on.