java - 使用 Spring Boot 的 3 层架构最佳实践

标签 java spring spring-boot design-patterns 3-tier

我在 Spring Boot 应用程序中使用 3 层架构。我创建了 3 个包(模型、服务、 Controller ),但我所做的是,服务使用 try catch 调用 repo 函数,然后我在 Controller 中调用它

示例:

服务:

public ResponseEntity<List<Customer>> getAllCustomers() {
    try {
        List<Customer> customers = new ArrayList<Customer>();
        cutomerRepository.findAll().forEach(customers::add);
        if (customers.isEmpty()) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<>(customers, HttpStatus.OK);
        } catch (Exception e) {
        return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

Controller

@GetMapping("/viewList")
private ResponseEntity<?> getAllCustomers()
{
    try{
        return customerService.getAllCustomers();
    }catch (Exception exception){
        return new ResponseEntity<String>("Customers is not found", HttpStatus.METHOD_FAILURE);

    }
}

这是正确的吗?我认为我应该只添加服务 customerRepository.findAll() ,而不添加任何其他逻辑或代码,但我不确定。有什么想法吗?

最佳答案

服务层应该包含逻辑,这样就可以了。

但它不应该包含来自 Controller 层的任何类,因为这会将信息从“上”层泄漏到“下”层。这意味着您的服务不应返回 ResponseEntity,因为它来自 Controller 层。相反,它应该简单地返回一个客户列表,并让 Controller 从中构造 ResponseEntity。
否则,您的服务将始终仅限于由该特定 Controller 调用。它不能被不使用 HTTP ResponseEntity 的不同类型 Controller 的另一个服务调用。

关于java - 使用 Spring Boot 的 3 层架构最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72721704/

相关文章:

tomcat - 定制Tomcat时: A ServletContext is required to configure default servlet handling

java - 调用其他组件的重绘

java - 为什么 Spring Boot Application 类需要有 @Configuration 注解?

java - 在 Spring 中动态更改 Bean 引用

java - 为 API 和 Angular 内容设置 spring 主机域作为主域

java - Spring Boot 应用程序的 Azure 发布管道表示没有可发布的工件

java - Spring Boot @RestController 和 @Controller

java - JGit:创建 Git 存储库并将其推送到 GitHub 时如何修复 NoRemoteRepositoryException?

java - 使用 Retrofit 选择某个 ID

java - spring-boot 更新到 1.3.1 后 webapp 无法启动