两个SpringBoot模块互相调用
两个SpringBoot模块互相调用注意:本文未使用SpringCloud的Feign和OpenFeign我们直接上操作步骤1,首先,在启动类加入RestTemplate,在项目启动的时候,使用@Bean注册到容器中@SpringBootApplicationpublic class GennlifeGdszApplication {public static void main(String[]
·
两个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();
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)