Jersey
1、SpringBoot
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
注意:jersety starter模式使用jackson解析JSON
配置
@Component
@ApplicationPath("/ws")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
//注册单个资源类
register(DemoResource.class);
//或直接声明资源包所在位置
// packages("pers.zhang.resource");
}
}
资源类
@Path("hi")
public class DemoResource {
@GET
@Produces("application/json")
public List<String> hi() {
List<String> result = new ArrayList<>();
result.add("hello world");
result.add("hello Jersey");
return result;
}
}
测试
@Test
public void testGet() {
Client client = ClientBuilder.newClient();
WebTarget webTarget = client.target("http://127.0.0.1:8080/ws/hi");
Response response = webTarget.request().get();
System.out.println(response.readEntity(String.class));
}
输出:
["hello world","hello Jersey"]
wadl文档
访问jersey.application-path/application.wadl
可以获取自动生成的wadl文档:
2、Actuator
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
解决根路径冲突
在Jersey中引入Spring MVC会带来根路径冲突的问题,因为它们各自的Servlet都默认处理根路径。有如下几种解决方案:
使用同一个端口,分别指定各自的根路径:
server:
port: 8080
# 启用所有监控端点
management:
endpoints:
web:
exposure:
include: "*"
spring:
jersey:
application-path: /rest
mvc的根路径为/
,jersey的跟路径为/rest
。
注意,如果同时也使用了@ApplicationPath("/ws")
声明根路径,那么yml中的配置会覆盖注解中的配置。
使用不同的端口:
server:
port: 8080
# 启用所有监控端点
management:
endpoints:
web:
exposure:
include: "*"
server:
port: 8081
actuator的端口为8081
,jersey的端口为8080
。