两个SpringBoot模块互相调用实现方式
作者:今晚我一个人
文章介绍了如何在两个SpringBoot模块之间进行互调,未使用SpringCloud的Feign和OpenFeign,具体步骤包括:在启动类中加入RestTemplate并注册到容器中;在需要调用的类中注入RestTemplate;在方法中使用RestTemplate调用其他模块的接口
两个SpringBoot模块互相调用
注意:本文未使用SpringCloud的Feign和OpenFeign
我们直接上操作步骤:
1,在启动类加入RestTemplate
在项目启动的时候,使用@Bean注册到容器中
@SpringBootApplication
public class GennlifeGdszApplication {
public static void main(String[] args) {
SpringApplication.run(GennlifeGdszApplication.class, args);
}
//RestTemplate记得手动加入
@Bean
RestTemplate restTemplate(){
return new RestTemplate();
}
}
2,在你需要使用的类中注入RestTemplate
在方法里面使用
@Service
public class UserService {
//注入RestTemplate
@Autowired
private RestTemplate restTemplate ;
//本人为了测试方便,随便写的方法,
public List<TestBean> getBookByProvide(){
int id = 1;
//填写要请求另一个模块的地址,此处我的Url写成固定的了,
String url = "http://127.0.0.1:8090/find?id="+id;
//注意,返回值要和被请求的模块保持一致,
return this.restTemplate.getForObject(url, List.class);
}
}
在Controller直接调用填写好的方法即可
@RestController
public class UserContorller {
@Autowired
private UserService userService ;
@RequestMapping(value = "/user", method = RequestMethod.GET)
public List<TestBean> getUser(){
return userService.getUser();
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
