前言
github: https://github.com/vergilyn/SpringBootDemo
代碼位置:
一、准備
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。
3. 所有注冊的端點都應該被@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。
(很早之前的看的一篇jersey的教程:使用 Jersey 和 Apache Tomcat 構建 RESTful Web 服務)
(題外話:記得當初在spring中使用jersey的一個問題是,在endpoints中無法注入其他service/dao的bean。然后,貌似記得是通過spring的上下文強制getBean()才把別的service/到注入到了enpoint中。不清楚是那框架搭建有問題,還是怎么的,只是記得遇到過這奇怪的問題。)