上海微信网站建设价格,玉环网站制作,如何安装wordpress的备份,电子商务网站设计方案boot jersey除了许多新功能#xff0c;Spring Boot 1.2还带来了Jersey支持。 这是吸引喜欢标准方法的开发人员的重要一步#xff0c;因为他们现在可以使用JAX-RS规范构建RESTful API#xff0c;并将其轻松部署到Tomcat或任何其他Springs Boot支持的容器中。 带有Spring平台的… boot jersey 除了许多新功能Spring Boot 1.2还带来了Jersey支持。 这是吸引喜欢标准方法的开发人员的重要一步因为他们现在可以使用JAX-RS规范构建RESTful API并将其轻松部署到Tomcat或任何其他Springs Boot支持的容器中。 带有Spring平台的Jersey可以在mico服务的开发中发挥重要作用。 在本文中我将演示如何使用Spring Boot包括Spring DataSpring TestSpring Security和Jersey快速构建应用程序。 引导新项目 该应用程序是常规的Spring Boot应用程序它使用Gradle及其最新的2.2版本。 Gradle不如Maven冗长它特别适合Spring Boot应用程序。 可以从Gradle网站下载Gradle http : //www.gradle.org/downloads 。 启动项目的初始依赖关系 dependencies {compile(org.springframework.boot:spring-boot-starter-web)compile(org.springframework.boot:spring-boot-starter-jersey)compile(org.springframework.boot:spring-boot-starter-data-jpa)// HSQLDB for embedded database supportcompile(org.hsqldb:hsqldb)// Utilitiescompile(com.google.guava:guava:18.0)// AssertJtestCompile(org.assertj:assertj-core:1.7.0)testCompile(org.springframework.boot:spring-boot-starter-test)
} 应用程序入口点是一个包含main方法的类并使用SpringBootApplication注释进行注释 SpringBootApplication
public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}
} SpringBootApplication注释是一个便捷注释等效于声明Configuration EnableAutoConfiguration ComponentScan EnableAutoConfiguration和ComponentScan 它是Spring Boot 1.2的新增功能。 球衣配置 入门就像创建用Path和Spring的Component注释的根资源一样容易 Component
Path(/health)
public class HealthController {GETProduces(application/json)public Health health() {return new Health(Jersey: Up and Running!);}
} 并将其注册在从Jersey ResourceConfig扩展的Spring的Configuration类中 Configuration
public class JerseyConfig extends ResourceConfig {public JerseyConfig() {register(HealthController.class);}
} 我们可以使用gradlew bootRun启动该应用程序访问 http// localhost8080 / health 我们应该看到以下结果 {status: Jersey: Up and Running!
} 但是也可以编写一个具有完全加载的应用程序上下文的Spring Boot集成测试 RunWith(SpringJUnit4ClassRunner.class)
SpringApplicationConfiguration(classes Application.class)
WebAppConfiguration
IntegrationTest(server.port9000)
public class HealthControllerIntegrationTest {private RestTemplate restTemplate new TestRestTemplate();Testpublic void health() {ResponseEntityHealth entity restTemplate.getForEntity(http://localhost:9000/health, Health.class);assertThat(entity.getStatusCode().is2xxSuccessful()).isTrue();assertThat(entity.getBody().getStatus()).isEqualTo(Jersey: Up and Running!);}
} Jersey 2.x具有本地Spring支持 jersey-spring3 而Spring Boot通过spring-boot-starter-jersey starter为它提供自动配置支持。 有关更多详细信息请查看JerseyAutoConfiguration类。 根据spring.jersey.type属性值Jersey Servlet或Filter都注册为Spring Bean Mapping servlet: jerseyServlet to [/*] 可以通过添加到ResourceConfig配置类的javax.ws.rs.ApplicationPath批注来更改默认映射路径 Configuration
ApplicationPath(/jersey)
public class JerseyConfig extends ResourceConfig {} JSON媒体类型支持随附有jersey-media-json-jackson依赖项该依赖项注册了可供Jersey使用的Jackson JSON提供程序。 Spring Data JPA集成 Spring Data JPA是较大的Spring Data系列的一部分可轻松实现基于JPA的存储库。 对于那些不熟悉该项目的人请访问 http : //projects.spring.io/spring-data-jpa/ 客户和客户存储库 此示例项目的域模型只是具有一些基本字段的Customer Entity
public class Customer extends AbstractEntity {private String firstname, lastname;Columnprivate EmailAddress emailAddress; Customer需要一个Repository 所以我们使用Spring的Data仓库创建了一个基本的仓库。 通过简单的接口定义Spring Data存储库减少了许多样板代码 public interface CustomerRepository extends PagingAndSortingRepositoryCustomer, Long {} 使用域模型后可以方便地使用一些测试数据。 最简单的方法是为data.sql文件提供要在应用程序启动时执行SQL脚本。 该文件位于src/main/resources Spring会自动将其拾取。 该脚本包含几个SQL插入内容以填写customer表。 例如 insert into customer (id, email, firstname, lastname) values (1, joedoe.com, Joe, Doe);客户总监 在使用Spring Data JPA存储库之后我创建了一个控制器就JAX-RS而言该控制器允许对Customer对象进行CRUD操作。 注意我坚持使用HTTP端点的Spring MVC命名约定但是可以随意使用JAX-RS方式。 获得客户 让我们从返回所有客户的方法开始 Component
Path(/customer)
Produces(MediaType.APPLICATION_JSON)
public class CustomerController {Autowiredprivate CustomerRepository customerRepository;GETpublic IterableCustomer findAll() {return customerRepository.findAll();}
} 使用Component保证CustomerController是一个Spring托管对象。 Autowired可以轻松替换为标准javax.inject.Inject注释。 由于我们在项目中使用Spring Data因此我可以轻松利用PagingAndSortingRepository.提供的PagingAndSortingRepository. 我修改了资源方法以支持某些页面请求参数 GET
public PageCustomer findAll(QueryParam(page) DefaultValue(0) int page,QueryParam(size) DefaultValue(20) int size,QueryParam(sort) DefaultValue(lastname) ListString sort,QueryParam(direction) DefaultValue(asc) String direction) {return customerRepository.findAll(new PageRequest(page, size, Sort.Direction.fromString(direction), sort.toArray(new String[0])));
} 为了验证以上代码我创建了Spring集成测试。 在第一次测试中我将要求所有记录并且基于先前准备的测试数据我希望在20页的1页中总共有3个客户 Test
public void returnsAllPages() {// actResponseEntityPageCustomer responseEntity getCustomers(http://localhost:9000/customer);PageCustomer customerPage responseEntity.getBody();// assertPageAssertion.assertThat(customerPage).hasTotalElements(3).hasTotalPages(1).hasPageSize(20).hasPageNumber(0).hasContentSize(3);
} 在第二个测试中我将调用大小为1的第0页并按firstname排序排序方向descending 。 我希望元素总数不变3返回的页面总数为3返回的页面内容大小为1 Test
public void returnsCustomPage() {// actResponseEntityPageCustomer responseEntity getCustomers(http://localhost:9000/customer?page0size1sortfirstnamedirectiondesc);// assertPageCustomer customerPage responseEntity.getBody();PageAssertion.assertThat(customerPage).hasTotalElements(3).hasTotalPages(3).hasPageSize(1).hasPageNumber(0).hasContentSize(1);
} 该代码也可以使用curl检查 $ curl -i http://localhost:8080/customerHTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json;charsetUTF-8
Content-Length: 702
Date: Sat, 03 Jan 2015 14:27:01 GMT{...} 请注意为了方便使用RestTemplate测试分页我创建了一些帮助程序类 Page Sort和PageAssertion 。 您可以在Github中的应用程序源代码中找到它们。 添加新客户 在这个简短的代码片段中我使用了Jersey的某些功能如注入Context 。 在创建新实体的情况下我们通常希望返回标题中资源的链接。 在下面的示例中我将UriBuilder注入到终结点类中并使用它来构建新创建的客户的位置URI Context
private UriInfo uriInfo;POST
public Response save(Customer customer) {customer customerRepository.save(customer);URI location uriInfo.getAbsolutePathBuilder().path({id}).resolveTemplate(id, customer.getId()).build();return Response.created(location).build();
} 在调用POST方法不存在电子邮件时 $ curl -i -X POST -H Content-Type:application/json -d {firstname:Rafal,lastname:Borowiec,emailAddress:{value: rafal.borowiecsomewhere.com}} http://localhost:8080/customer 我们将获得 HTTP/1.1 201 Created
Server: Apache-Coyote/1.1
Location: http://localhost:8080/customer/4
Content-Length: 0
Date: Sun, 21 Dec 2014 22:49:30 GMT 当然也可以创建集成测试。 它使用RestTemplate使用postForLocation方法保存客户然后使用getForEntity检索它 Test
public void savesCustomer() {// actURI uri restTemplate.postForLocation(http://localhost:9000/customer,new Customer(John, Doe));// assertResponseEntityCustomer responseEntity restTemplate.getForEntity(uri, Customer.class);Customer customer responseEntity.getBody();assertThat(customer.getFirstname()).isEqualTo(John);assertThat(customer.getLastname()).isEqualTo(Doe);
} 其他方法 端点的其余方法确实很容易实现 GET
Path({id})
public Customer findOne(PathParam(id) Long id) {return customerRepository.findOne(id);
}DELETE
Path({id})
public Response delete(PathParam(id) Long id) {customerRepository.delete(id);return Response.accepted().build();
}安全 通过向项目添加新的依赖关系可以快速地将Spring Security添加到应用程序中 compile(org.springframework.boot:spring-boot-starter-security) 使用Spring Security在classpath中应用程序将通过所有HTTP端点上的基本身份验证得到保护。 可以使用以下两个应用程序设置 src/main/resources/application.properties 更改默认的用户名和密码 security.user.namedemo
security.user.password123 在使用Spring Security应用程序运行该应用程序之后我们需要为每个请求提供一个有效的身份验证参数。 使用curl可以使用--user开关 $ curl -i --user demo:123 -X GET http://localhost:8080/customer/1 随着Spring Security的添加我们先前创建的测试将失败因此我们需要向RestTemplate提供用户名和密码参数 private RestTemplate restTemplate new TestRestTemplate(demo, 123);分派器Servlet Spring的Dispatcher Servlet与Jersey Servlet一起注册并且它们都映射到根资源 。 我扩展了HealthController 并向其中添加了Spring MVC请求映射 Component
RestController // Spring MVC
Path(/health)
public class HealthController {GETProduces({application/json})public Health jersey() {return new Health(Jersey: Up and Running!);}RequestMapping(value /spring-health, produces application/json)public Health springMvc() {return new Health(Spring MVC: Up and Running!);}
} 通过以上代码我希望根上下文中可以同时使用health和spring-health端点但是显然它不起作用。 我尝试了几种配置选项包括设置spring.jersey.filter.order但没有成功。 我发现的唯一解决方案是更改Jersey ApplicationPath或更改Spring MVC server.servlet-path属性 server.servlet-path/s 在后一个示例中调用 $ curl -i --user demo:123 -X GET http://localhost:8080/s/spring-health 返回预期结果 {status:Spring MVC: Up and Running!
}使用Undertow代替Tomcat 从Spring Boot 1.2开始支持Undertow轻量级高性能Servlet 3.1容器。 为了使用Undertow代替Tomcat必须将Tomcat依赖项与Undertow的依赖项交换 buildscript {configurations {compile.exclude module: spring-boot-starter-tomcat}
} dependencies {compile(org.springframework.boot:spring-boot-starter-undertow:1.2.0.RELEASE)
} 运行应用程序时日志将包含 org.xnio: XNIO version 3.3.0.Final
org.xnio.nio: XNIO NIO Implementation Version 3.3.0.Final
Started Application in 4.857 seconds (JVM running for 5.245)摘要 在这篇博客文章中我演示了一个简单的示例介绍如何开始使用Spring Boot和Jersey。 由于Jersey的自动配置向Spring应用程序添加JAX-RS支持非常容易。 通常Spring Boot 1.2使使用Java EE的应用程序构建更加容易使用Atomikos或Bitronix嵌入式事务管理器进行JTA事务在JEE Application Server中对DataSource和JMS ConnectionFactory进行JNDI查找并简化JMS配置。 资源资源 项目源代码 https : //github.com/kolorobot/spring-boot-jersey-demo 后续 使用JAX-RS和Spring构建HATEOAS API 翻译自: https://www.javacodegeeks.com/2015/01/getting-started-with-jersey-and-spring-boot.htmlboot jersey