添加依赖
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-jersey</artifactId>
- </dependency>
添加配置
1新建 JerseyConfig.java
- @Component
- @ApplicationPath("/jersey")
- public class JerseyConfig extends ResourceConfig{
- public JerseyConfig(){
- //packages("com.example.study");
- register(UserResource.class);
- }
- }
建议用 register 添加资源
注意 ApplicationPath, 如果不添加无法访问, 因为默认为 /*, 由于本项目无 web.xml, 所以在这里配置 (配置文件里也可以)
2输出的 JSON 数据格式化 (方便使用, 不添加也可访问)
在 application.YAML 中 Spring 块下添加
- jackson:
- default-property-inclusion: non_null
- serialization:
- indent-output: true
- date-format: yyyy-MM-dd HH:mm:ss
- parser:
- allow-missing-values: true
测试使用
新建 UserResource.java
- @Component
- @Path("/users")
- public class UserResource {
- @Autowired
- private UserMappers userMapper;
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public User get(){
- List<User> users = userMapper.selectAll();
- return users.get(0);
- }
- }
记得在 JerseyConfig 中注册
访问
http://localhost:8088/jersey/users
其它
注意: 此时原来搭建的 SpringMVC 也可以访问
SpringMVC 与 jersey 就一起工作了, 附上项目目录供大家参考项目异同.
这是我使用了 jersey 的项目, 其余配置还有:
- mybatis,mybatis generator
- slf4+logback
thymeleaf 模板引擎
alibaba 的 druid 数据库连接池
https://github.com/Lifan1998/study
供初学者参考.
来源: http://www.bubuko.com/infodetail-2947327.html