1、在启动类中,注入RestTemplate对象
@SpringBootApplication
public class SpringcloudApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
2、直接通过@Autowird注解进行使用
@Controller
public class UserContrloler {
//RestTemplate的运用
@Autowired
public RestTemplate restTemplate;
@GetMapping("rt") //返回集合
public List<User> uList(){
List<User> body = restTemplate.exchange(
"http://localhost:80/userList",
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<User>>() {
}).getBody();
return body;
}
@GetMapping("u/{id}") //返回单个对象
public Object getUser(@PathVariable Integer id){
User u = restTemplate.getForObject("http://localhost:80/user/" + id, User.class);
return u;
}
}