我的项目由 5 个模块组成。其中只有一个使用 JAX-RS,其他使用 Spring。我目前的任务是开发服务,将 HTTP 请求发送到某些 API。我想用 Spring RestTemplate
对于此任务,但问题是带有 JAX-RS 的项目还没有 RestTemplate
类和其他必要的依赖项。我想用:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
在 JAX-RS 模块中,避免
RestTemplate
的代码重复对于一些 JAX-RS 客户端。这是个好主意吗?将是 RestTemplate
没有 spring-core
也能正常工作依赖?
最佳答案
使用 RestTemplate
要使用 RestTemplate
您只需要 spring-web
依赖项:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.3.RELEASE</version>
</dependency>
spring-web
依赖项具有 spring-core
作为传递依赖项。要使用
RestTemplate
它很简单:public class ExampleWithRestTemplate {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response =
restTemplate.getForEntity("http://date.jsontest.com", String.class);
System.out.println(response.getBody());
}
}
考虑 JAX-RS 客户端 API 作为替代方案
除了
RestTemplate
,您还可以考虑使用 JAX-RS 2.0 Client API 来使用 REST Web 服务。 Jersey 是 JAX-RS 引用实现,并提供了很棒的 API。要使用 Jersey 客户端 API,需要以下依赖项:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.23.2</version>
</dependency>
有关更多详细信息,请查看 documentation 。
您也可以考虑 Jersey Client Proxy API 。这种方法的基本思想是将标准 JAX-RS 注释附加到接口(interface),然后在服务器端通过资源类实现该接口(interface),同时在客户端通过动态生成使用
java.lang.reflect.Proxy
的实现来重用相同的接口(interface)调用正确的低级客户端 API 方法。要使用 Jersey 客户端代理 API,需要以下依赖项:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-proxy-client</artifactId>
<version>2.23.2</version>
</dependency>
关于spring - 在 JAX-RS 项目中使用 Spring RestTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39868792/