@SpringBootApplication是@SpringBootConfiguration、@EnableAutoConfiguration、@ComponentScan三个注解的综合, 其中@SpringBootConfiguration说明主程序这个类也是一个配置类,可以实现bean的动态注入。
于是实现服务的远程调用可以根据以下步骤进行:
1 注册 RestTemplate
在 order-service 的 OrderApplication 中注册 RestTemplate:
MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
2 服务远程调用 RestTemplate
修改 order-service 中的 OrderService 的 queryOrderById 方法:
public Order queryOrderById(Long orderId) {
// 1.查询订单
Order order = orderMapper.findById(orderId);
String url = "http://localhost:8081/user/" + order.getUserId();
User user = restTemplate.getForObject(url,User.class);
order.setUser(user);
// 4.返回
return order;
}
本文介绍了如何在SpringBoot应用中使用@SpringBootApplication、@EnableAutoConfiguration和@ComponentScan注解,以及如何注册RestTemplate并实现服务间的远程调用,以OrderService的queryOrderById方法为例。
662

被折叠的 条评论
为什么被折叠?



