1. pom引入依赖包(jersey.version=2.23)
org.glassfish.jersey.ext jersey-spring3 ${jersey.version} org.springframework spring-core org.springframework spring-web org.springframework spring-beans org.glassfish.jersey.media jersey-media-json-jackson ${jersey.version} org.springframework spring-core 4.1.0.RELEASE org.springframework spring-web 4.1.0.RELEASE org.springframework spring-beans 4.1.0.RELEASE org.springframework spring-context 4.1.0.RELEASE org.springframework spring-aop 4.1.0.RELEASE org.springframework spring-context-support 4.1.0.RELEASE
2. web.xml
jersey-serlvet org.glassfish.jersey.servlet.ServletContainer javax.ws.rs.Application cn.gov.zjport.seg.search.jersey.MyApplication 1 jersey-serlvet /*
注:如果不用自定义的 MyApplication, spring bean 将无法注入。
3. rest服务
@Service @Path("/selsearch") public class SelSearchServiceImpl implements SelSearchService{ @Resource private SelEsWrappedClient selEsWrappedClient; @GET @Path("/{param}") @Produces(MediaType.TEXT_PLAIN) public String search(@PathParam("param") String userName) { return selEsWrappedClient.getName()+userName; } }
SelSearchServiceImpl 和 SelEsWrappedClient 都是spring管理的bean,需要当作resource 在 MyApplication 中注册
4. 注册器
public class MyApplication extends ResourceConfig { /** * Register JAX-RS application components. */ public MyApplication () { //自己写的服务 register(SelSearchServiceImpl.class); //用 Jackson JSON 的提供者来解释 JSON register(JacksonFeature.class); //Spring filter 提供了 JAX-RS 和 Spring 请求属性之间的桥梁 register(RequestContextFilter.class); } }
5. 访问 http://localhost:8080/seg-search-webapp/selsearch/xxx 即可