超类型标记模式会捕获类信息中的泛型参数,以避免Java语言中类型擦除的限制。
The purpose of this class is to enable capturing and passing a generic Type. In order to capture the generic type and retain it at runtime, you need to create a subclass (ideally as anonymous inline class) as follows:
ParameterizedTypeReference<List<String>> typeRef = new ParameterizedTypeReference<List<String>>() {};
The resulting typeRef instance can then be used to obtain a Type instance that carries the captured parameterized type information at runtime. For more information on “super type tokens” see the link to Neal Gafter’s blog post.
- 一个控制器,返回类型为Map<String, String>
package greetings;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
import java.util.Collections;
import java.util.Map;
@Profile("secure")
@RestController
@RequestMapping(method = RequestMethod.GET, value = "/greet/{name}")
public class SecureGreetingsRestController {
@RequestMapping
Map<String, String> hi(@PathVariable String name, Principal p) {
return Collections.singletonMap("greeting",
"Hello, " + name + " from " + p.getName() + "!");
}
}
- 通过restTemplate请求
package greetings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Profile;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.Map;
@Profile({ "default", "insecure" })
@RestController
@RequestMapping("/api")
class RestTemplateGreetingsClientApiGateway {
private final RestTemplate restTemplate;
@Autowired
RestTemplateGreetingsClientApiGateway(
@LoadBalanced RestTemplate restTemplate) { // <1>
this.restTemplate = restTemplate;
}
@GetMapping("/resttemplate/{name}")
Map<String, String> restTemplate(@PathVariable String name) {
//@formatter:off
ParameterizedTypeReference<Map<String, String>> type =
new ParameterizedTypeReference<Map<String, String>>() {};
//@formatter:on
ResponseEntity<Map<String, String>> responseEntity = this.restTemplate
.exchange("http://greetings-service/greet/{name}", HttpMethod.GET, null,
type, name);
return responseEntity.getBody();
}
}