一、注册它
@MapperScan("com.gq.order.mapper") @SpringBootApplication public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } /** * 服务(项目启动过程中会创建 RestTemplate 的实例, 将它放入 IoC 容器 * 要使用 RestTemplate 的时候, 注入即可 */ @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
二、使用它
@Service @Transactional public class OrderServiceImpl implements OrderService { @Resource private OrderMapper orderMapper; @Resource private RestTemplate http; /** * 根据订单 id 查询订单 */ @Transactional(readOnly = true) @Override public Order getOrderById(Long orderId) { // 根据 orderId 查询订单 Order orderById = orderMapper.getOrderById(orderId); if (orderById != null) { // 根据 userId 发送网络请求查询用户信息 Long userId = orderById.getUserId(); String url = "http://localhost:8081/users/getUserById/" + userId; // 发送网络请求 User userById = http.getForObject(url, User.class); orderById.setUser(userById); } return orderById; } }