jersey + Spring Boot
SpringBootとglassfishのjerseyを連携させてみた
jerseyって
> RestfulなWebApplicationを実現するためのフレームワーク
> JAX-RS — Project Kenaiっていう規格にのっとってる
基本的には役割はSpringMVCと近い感じかと
構築方法
依存関係 (きちんと調べきれてないです)
build.gradle
dependencies { compile "org.springframework.boot:spring-boot-starter-aop:$springbootVersion" compile "org.springframework.boot:spring-boot-starter-web:$springbootVersion" compile "org.springframework:spring-context:$springVersion" // jersey本体 compile "org.glassfish.jersey.core:jersey-server:2.12" // サーブレットのラッパー compile "org.glassfish.jersey.containers:jersey-container-servlet:2.12" // springのアノテーションを使う場合必須 @Autowiredとか compile "org.glassfish.jersey.ext:jersey-spring3:2.12" // media typeとか管理するライブラリ compile "org.glassfish.jersey.media:jersey-media-moxy:2.12" // jsonに変換するライブラリ compile "org.glassfish.jersey.media:jersey-media-json-jackson:2.12" }
SpringBootそのまま
Main.java
@EnableAutoConfiguration @Configuration @ComponentScan(basePackages = "com.hase.sample") public class Main { public static void main(String[] args) { SpringApplication.run(Main.class, args); } }
自分はかなりハマった部分で(ドキュメント読まなかったから)
ここで、JacksonFeature.clssを挿しておかないと、POJOをJSONに変換できない
調べると、Servletのinit parameterに差し込む方法もあるようだけど、web.xmlは利用していないから使えない
loggerの出力はイマイチ
import org.glassfish.jersey.filter.LoggingFilter; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.servlet.ServletContainer; import org.glassfish.jersey.servlet.ServletProperties; import org.springframework.boot.context.embedded.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.filter.RequestContextFilter; @Configuration public class JerseyConfiguration extends ResourceConfig { public static class JerseyServletConfig extends ResourceConfig { public JerseyServletConfig() { // filter類はここにいれていく register(JacksonFeature.class); register(RequestContextFilter.class); packages("com.hase.sample"); register(LoggingFilter.class); } } @Bean public ServletRegistrationBean jerseyServlet() { ServletRegistrationBean registration = new ServletRegistrationBean(new ServletContainer(), "/*"); registration.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyServletConfig.class.getName()); return registration; } }
コントローラー
import org.springframework.stereotype.Component; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; @Component @Path("/") public class JerseyController { @GET @Produces(MediaType.APPLICATION_JSON) @Path("/hello/{name}") public String hello(@DefaultParam("taro") @PathParam("name") String name) { return "Hello" + name; } }