使用springboot中的rest api,架构问题

如何解决使用springboot中的rest api,架构问题

我想用springBoot MVC编写REST API客户端。客户端将向API发送数据请求,并将其显示在浏览器中。例如,我将http://example.com/showItems映射到itemsController.show方法,并由item.html(百里香叶)模板呈现。

我的问题是在哪里放置API调用以及如何处理API响应。 我在考虑设计,而不仅仅是使它起作用。还要想象一下,我想扩展到许多返回不同对象的API调用。

我正在考虑几种选择:

  • 控制器内部的WebClient。控制器处理返回项目Object的API调用。
  • item类负责API调用。并可能调整结果以进行渲染。不同的对象具有不同的API调用。也许所有人都注入了相同的WebClient
  • 我创建一个包含“ DAO”的itemService,这是一个调用API并返回item对象的itemDAO。类似于DAO存储库+模型。

我不确定采用哪种解决方案。在春季或其他设计模式中,还有其他常用的方法吗?或者每种解决方案的利弊是什么?

解决方法

有很多方法可以在春季启动时遵循MVC的结构 在这里,我有一个解决方案,您可以在其中进行后续操作


这是我的文件结构

UserController 和@RestController //所有获取和发布Apis呼叫

UserService 和@Service //在此处定义业务逻辑

UserRegistrationReqBean @Data //用于龙目岛并减少样板

UserMaster @Entity //对于表架构

  • UserMasterRepo @Repository //用于Jpa查询

    • UserMasterDao //与服务层交互以进行数据库查询的界面

      • UserMasterDaoImpl @Component //用于Dao接口定义

首先创建一个控制器类(例如我正在使用用户管理系统)

@RestController
@RequestMapping("/v1.0")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/getUsers")
    public List<UserMaster> getUsers() {
        return userService.getUsers();
    }

    @PostMapping("/registerUser")
    public UserMaster registerUser(@RequestBody RegisterUserReqBean reqBean) {
        return userService.registerUser(reqBean);
    }

//  @PostMapping("/updateUser")
//  public UserMaster updateUser() {
//      UserMaster updatedUser = new UserMaster();
//      return updatedUser;
//  }

}

创建完控制器后,需要使用@Service注释在服务层中定义其业务逻辑

@Service
public class UserService {

    @Autowired
    UserMasterDao userMasterDao;

    public List<UserMaster> getUsers() {
        List<UserMaster> listOfUser = userMasterDao.findAll();
        return listOfUser;
    }

    public UserMaster registerUser(RegisterUserReqBean reqBean) {
        UserMaster userMaster = new UserMaster(reqBean);
        UserMaster updatedUserMaster = userMasterRepo.save(userMaster);
        return updatedUserMaster;
    }

//  public UserMaster updateUser() {
//
//  }
}

创建带有@Repository批注的Repo类以进行一些与数据库相关的更改

import org.springframework.data.jpa.repository.JpaRepository;

import com.sample.user.entity.UserMaster;

    @Repository
    public interface UserMasterRepo extends JpaRepository<UserMaster,Integer> {
    
//you can create your own JPA queries here
    }

这里的存储库为空,因为我正在使用其预定义的查询

than使用带有@Entity批注的实体类来定义数据库表架构 使用 Maven Lombok依赖来减少Entity中的样板代码并请求Bean

    @Entity
    @Data
    @Table(name = "kd_user_master")
    public class UserMaster {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "user_id")
        private Integer userId;
    
        @Column(name = "first_name")
        private String firstName;
    
        @Column(name = "last_name")
        private String lastName;
    
        @Column(name = "user_name")
        private String userName;
    
        @Column(name = "email")
        private String email;
    
        @Column(name = "mobile_number")
        private String mobileNumber;
    
        @Column(name = "password")
        private String password;
    
        @Column(name = "country")
        private String country;
    
        @Column(name = "created_at")
        private Date createdAt;
    
        @Column(name = "updated_at")
        private Date updatedAt;

//this parameterized cunstructer is used for having new object of userMaster //schema so we can directly save it to db 
public UserMaster(RegisterUserReqBean reqBean) {
        super();
        this.firstName = reqBean.getFirstName();
        this.lastName = reqBean.getLastName();
        this.userName = reqBean.getUserName();
        this.email = reqBean.getEmail();
        this.mobileNumber = reqBean.getMobileNumber();
        this.password = reqBean.getPassword();
        this.country = reqBean.getCountry();
        this.createdAt = new Date();
        this.updatedAt = new Date();
    }
    }

然后我们将创建一个DAO(数据访问对象)接口及其实现类

public interface UserMasterDao{

UserMaster save(userMaster user);

List<UserMaster> findAll();
}

其实施类

public class UserMasterDaoImpl implements UserMasterDao{

@Autowired
UserMasterRepo repo;

@Override
UserMaster save(UserMaster user){
return repo.save(user);
}


@Override
List<UserMaster> findAll(){
return repo.findAll();
}
}

在业务逻辑和数据库模式之后,我们需要为后请求定义Request bean,因为它不允许我们请求参数,或者我们可以说查询参数

@Data
public class RegisterUserReqBean {

    private String firstName;

    private String lastName;

    private String userName;

    private String email;

    private String mobileNumber;

    private String password;

    private String country;

    private Date createdAt;

    private Date updatedAt;
}

我们正在控制器类和服务类中使用此请求bean进行用户注册

,

通常,所有业务逻辑和任何API调用都应在Service层中完成。您应该在配置类中配置另一个服务bean,并在服务层(适当的mvc架构)中进行调用,一旦获得响应,就可以根据需要对其进行更改,然后将其返回给控制器。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-