微服务系列文章之 Springboot集成Jersey

news/2024/7/8 2:16:03

​ Springboot支持Jersey1.x和Jersey2.x,我们这里只介绍Springboot对Jersey2.x的支持。springboot对jersey的集成非常简单。

​ 项目结构:

 

 

 1、引入Springboot对Jersey的starter包

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2、配置Jersey配置对象

​ Springboot需要对Jersey的配置对象,有三种配置方式:

  1. 创建一个自定义的ResourceConfig
  2. 返回一个ResourceConfig类型的@Bean
  3. 配置一组ResourceConfigCustomizer对象

我们分别测试一下这三种配置方式。

实体类 User.java

package com.example.springbootjersey2.bean;

import org.springframework.stereotype.Component;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;

@Component
@XmlRootElement(name = "user")
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private String id;
    private String name;
    private String profession;

    public String getId() {
        return id;
    }

    @XmlElement
    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public String getProfession() {
        return profession;
    }

    @XmlElement
    public void setProfession(String profession) {
        this.profession = profession;
    }

    @Override
    public String toString() {
        return "User{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", profession='" + profession + '\'' +
                '}';
    }
}

业务服务类  UserService.java

package com.example.springbootjersey2.service;


import com.example.springbootjersey2.bean.User;
import com.example.springbootjersey2.dao.UserDao;
import org.springframework.stereotype.Service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;

@Path("/UserService")
@Service
public class UserService {

    @Path("/users")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> getUsers() {
        System.out.println("success");
        UserDao dao = new UserDao();
        return dao.getAllUsers();
    }
}

数据访问 UserDao.java

package com.example.springbootjersey2.dao;

import com.example.springbootjersey2.bean.User;
import org.springframework.stereotype.Repository;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Repository
public class UserDao{

    public List<User> getAllUsers() {
        List<User> userList;
        File file = new File("Users.dat");
        if (!file.exists()) {
            User user = new User();
            user.setId("1");
            user.setName("Tom");
            user.setProfession("Student");
            userList = new ArrayList<>();
            userList.add(user);
            writeUserList(userList, file);
        } else {
            userList = readUserList(file);
        }
        return userList;
    }


    /**
     * 序列化
     *
     * @param userList
     * @param file
     */
    private void writeUserList(List<User> userList, File file) {
        ObjectOutputStream oos = null;
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(userList);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    /**
     * 反序列化
     *
     * @param file
     * @return
     */
    @SuppressWarnings("unchecked")
    private List<User> readUserList(File file) {
        List<User> userList = null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(file);
            ois = new ObjectInputStream(fis);
            userList = (List<User>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return userList;
    }
}

启动类

package com.example.springbootjersey2;

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class RestfulDemoApplication  {

    public static void main(String[] args) {
        SpringApplication.run(RestfulDemoApplication.class,args);
    }

   
}

第1种方式:创建一个自定义的ResourceConfig

package com.example.springbootjersey2.config;


import com.example.springbootjersey2.service.UserService;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;

@Component
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        register(UserService.class);
    }
}

只需要保证JerseyConfig在Application类能够扫描的包下即可。

发送测试请求:http://localhost:8080/UserService/users

 

注意:

  • Springboot默认把Jersey的根路径映射在/*上的;这个可以通过几种方式来配置,对于自定义的ResourceConfig方式来说,只需要在类上面添加一个@ApplicationPath注解即可:
@Component
@ApplicationPath("webapi")
public class JerseyConfig extends ResourceConfig {

​ 此时测试地址变为:http://localhost:8080/webapi/UserService/users

第2种方式:ResourceConfig类型的@Bean

 

 

​ 但是在这种情况下,想要配置Jersey的基础路径,就需要在application.properties文件中配置一个

spring.jersey.application-path=webapi

第3种方式: 使用ResourceConfigCustomizer

@Component
public class MyResourceConfigCustomizer implements ResourceConfigCustomizer {
    @Override
    public void customize(ResourceConfig config) {
        config.register(UserService.class);
    }
}

该接口很简单,传入一个ResourceConfig实例,我们就可以针对这个实例进行相关配置。但是要让这个传入的config生效,我们还需要在RestfulDemoApplication类中提供一个基础的ResourceConfig类即可:

@SpringBootApplication
public class RestfulDemoApplication  {

    public static void main(String[] args) {
        SpringApplication.run(RestfulDemoApplication.class,args);
    }

    @Bean
    public ResourceConfig resourceConfig() {
        ResourceConfig config = new ResourceConfig();
       
        return config;
    }
}

​ 这种方式对比第二种方式的好处在于,我们可以把资源类的注册,过滤器,拦截器,Entity Provider,Feature等不同类型的组件注册从主类中分开,在代码管理上会更加清晰。

 


http://lihuaxi.xjx100.cn/news/1275451.html

相关文章

CODESYS 数组类型变量(ARRAY)使用介绍

博途PLC数组类型变量使用介绍请参看下面文章博客: 博途1200/1500PLC上升沿下降沿指令编程应用技巧(bool数组)_博途上升沿指令_RXXW_Dor的博客-CSDN博客博途PLC的下降沿和上升沿指令,在控制系统编程时经常会使用。和SMARTS7-200有所不同,遵循IEC-6113标准提供的上升沿下降沿…

java适配达梦数据库

目录 一、数据库安装 二、数据库可视化工具 三、数据迁移 四、工程适配 新增maven依赖 配置文件修改 基于flyway的数据库版本管理 五、注意事项 一、数据库安装 官方文档&#xff1a;安装前准备 | 达梦技术文档 这里有一个点需要注意&#xff0c;如果你之前的数据库或…

中国人民大学与加拿大女王大学金融硕士——在职读研让能力加速提升

不管你是初入职场的小白&#xff0c;还是久经沙场的元老&#xff0c;想要在职场有所作为&#xff0c;就不要忽略自我能力提升。决定一个人当前职场价值不是他拥有了什么&#xff0c;而是他将来能够创造什么。如果你只盯着工作&#xff0c;那么你的眼界和薪资将会被工作所决定&a…

【数据可视化】大作业(意向考研高校的数据可视化)

文章目录 前言一、数据介绍1.1 基本信息1.2 考研信息1.3 导师信息 二、预处理及分析2.1 数据预处理2.1.1 考研信息预处理2.1.2 导师信息预处理 2.2 数据分析 三、可视化方法及结果3.1 可视化方法3.2 可视化结果展示3.2.1 基本信息3.2.2 考研信息3.2.3 导师信息 四、总结五、附录…

三个数据恢复方法解决移动硬盘数据丢失问题!

移动硬盘容量大、写入和读取速度快&#xff0c;受到很多人的欢迎。但是&#xff0c;无论数据存储在何处&#xff0c;都有数据丢失的风险。今天&#xff0c;小编来介绍一下移动硬盘数据恢复的方法&#xff0c;以免大家不慎删除移动硬盘数据而陷入无助的境地! 方法1.使用命令恢复…

Idea快捷键设置(Idea快捷键大全)

目录 友情提醒第一章、IDEA常用快捷键1.1&#xff09;快捷键&#xff1a;查找/提示类1.2&#xff09;快捷键&#xff1a;修改代码类1.3&#xff09;快捷键&#xff1a;光标移动类 第二章、如何修改快捷键2.1&#xff09;修改快捷键的方法2.2&#xff09;我修改的快捷键&#xf…

中国葡萄酒 当惊世界殊 宁夏贺兰山东麓葡萄酒亮相首都地铁

近日&#xff0c;宁夏贺兰山东麓葡萄酒以“中国葡萄酒 当惊世界殊、中国酒庄酒 天赋贺兰山”为宣传主题的宁夏贺兰山东麓葡萄酒宣传专列&#xff08;列车车号&#xff1a;01055&#xff09;亮相北京地铁1号线。该专列将从4月7日至7月6日持续开行3个月&#xff0c;平均每天往返穿…

为什么你的手机号需要二次实名,这几个原因你想过没有?

尊敬的客户&#xff1a;您的手机卡存在安全风险&#xff0c;为保护您的权益&#xff0c;您的电话呼出、短信和流量使用功能被限制。请机主本人使用被保护的手机号码登录网页链接 进行实名核验&#xff0c;核验通过后&#xff0c;将自动恢复正常通信服务。如核验未通过&#xff…