前言
代码位置:
一、准备
spring boot对jersey1.x与jersey2.x的注入方式有区别。本文是针对2.x的配置(服务端,不包含客户端调用。)
需要依赖的POMs
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
jersey的配置与别的不同的是:需要一个ResourceConfig类型的@Bean,用于注册所有的端点(endpoints)。
二、demo
2.1 用于注册所有endpoints的Config
/* 想要开始使用Jersey 2.x只需要加入spring-boot-starter-jersey依赖,
* 然后你需要一个ResourceConfig类型的@Bean,用于注册所有的端点(endpoints,demo为JerseyController)。
*/
//@Component
@Configuration
//Jersey servlet将被注册,并默认映射到/*。可将@ApplicationPath添加到ResourceConfig来改变该映射。
@ApplicationPath("/rest")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(JerseyController.class);
// packages("com.vergilyn.demo.springboot.jersey"); // 通过packages注册。
}
}
2.2 endpoints
/*
* 所有注册的端点都应该被@Components和HTTP资源annotations(比如@GET)注解。
* 1、因为是@Component,所以其生命周期受Spring管理。
* 并且你可以使用@Autowired添加依赖及使用@Value注入外部配置。
*/
//@Component
@RestController
@Path("/jersey")
public class JerseyController {
@GET
@Path("/get")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> getMessage() {
return Constant.map;
}
@POST //POST形式在浏览器地址栏输入请求路径不一定能访问到。推荐用fiddler工具或者firefox浏览器插件(poster或HttpRequester)
@Path("/post")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Object> postMessage() {
return Constant.map;
}
}
到此需要注意的有:
1. 如果是post形式,浏览器不一定可直接访问得到json。最好用Fiddler工具或者FireFox浏览器插件(Poster或HttpRequester)测试接口。
2. 既然是RESTful,所以建议直接用@RestController,而并不建议使用@Controller。
所有注册的端点都应该被@Components和HTTP资源annotations(比如@GET)注解。
2.3 SpringApplication
@SpringBootApplication
public class JerseyApplication {
/* 代码注入:
* 此种方式需注意:ServletRegistrationBean的配置,及最终的请求路径。
* 注解注入:
* JerseyConfig.java中用@Configuration
*/
// @Bean
public ServletRegistrationBean jerseyServlet() {
/* 特别注意此路径,与JerseyController中的@Path。可能让最终路径变成:localhost:8080/rest/jersey/get
* rest是此ServletRegistrationBean定义的(同ResourceConfig的类注解@ApplicationPath("/rest"))
* jersey是Controller中类注解@Path定义的
*/
ServletRegistrationBean registration = new ServletRegistrationBean(
new ServletContainer(), "/rest/*");
// our rest resources will be available in the path /rest/*
registration.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS,
JerseyConfig.class.getName());
return registration;
}
public static void main(String[] args) {
SpringApplication.run(JerseyApplication.class, args);
}
}
到此,所有的jersey2.X服务端代码就算完成。
如果是get请求,那么浏览器直接请求:localhost:8080/rest/jersey/get 就可以得到返回的json结果。(虽然代码中get返回的是Map,但定义@Produces(MediaType.APPLICATION_JSON))
至于请求参数的接收、客户端的调用,和spring集成Jersey是差不多的。这主要是用spring boot集成Jersey,不细说Jersey。
(题外话:记得当初在spring中使用jersey的一个问题是,在endpoints中无法注入其他service/dao的bean。然后,貌似记得是通过spring的上下文强制getBean()才把别的service/到注入到了enpoint中。不清楚是那框架搭建有问题,还是怎么的,只是记得遇到过这奇怪的问题。)