java runwith_@runWith注解起什么作用啊?

// 比如 这里有个配置类,在 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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值