// 比如 这里有个配置类,在 src.main.java 包下面
@Slf4j
@Configuration
public class RestClientConfig {
/**
* 支持多次使用 response.getBody() 读取流, 更多详情,请参考:https://blog.csdn.net/w1047667241/article/details/109823783
*/
@Bean
public RestTemplate restTemplate() {
RestTemplate template = new RestTemplate(
// 多次使用 getBody() response body
new BufferingClientHttpRequestFactory(new HttpComponentsClientHttpRequestFactory()));
return template;
}
}
// 你想在 测试类里面 使用这个 Bean 对象,有2种方式,1 是 注解 @Autowired 注入;2 是 代码手动 getBean
//方式1:
@RunWith(SpringJUnit4ClassRunner.class) // 在该类中运行测试,提供一些 spring 的某些特性支持
@ContextConfiguration(classes = RestClientConfig.class) // 利用SpringJUnit4ClassRunner 注入 Bean
public class RestTemplateConfigTest {
@Autowired //再比如这个特性,直接使用 @Autowired
RestTemplate restTemplate;
@Test
public void test01() {
ResponseEntity responseEntity = restTemplate.postForEntity("http://httpbin.org/post", null, String.class);
System.out.println("楼上的某些评论,成功的解决了提出问题的人,典型的 国产思维。这可不好呀,都是自己人。");
}
}
// 方式2:
// 不加 @RunWith()
public class RestTemplateConfigTest {
@Test
public void test02() {
ApplicationContext context = new AnnotationConfigApplicationContext(RestClientConfig.class);
RestTemplate restTemplate = context.getBean(RestTemplate.class);
String object = restTemplate.getForObject("https://不要解决提出问题的人.ok?param=yes", String.class);
}
}