我在Spring Boot应用程序中使用三层架构.我创建了3个包(model、service、controller),但我所做的是,service使用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);
    }
}

控制器

@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()个服务,但我不确定.有什么 idea 吗?

推荐答案

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

But it should not contain any classes from the Controller layer, as this would leak information from an "upper" layer into a "lower" layer. This means your Service should not return a ResponseEntity as this is from the Controller layer. Instead it should return simply a list of Customers and let the Controller construct the ResponseEntity out of it.
Otherwise your Service will always be limited to be called by this specific Controller. It would not be reusable to be called by another service of a different type of Controller, that does not use an HTTP ResponseEntity.

Java相关问答推荐

在Java中使用带限制的回归打印星形三角形

泽西岛:退回到不注射的客户"

Java 8 RDX-如何设置单个选项卡标题文本的 colored颜色

如何在Spring Boot中创建500错误的响应正文?

当列顺序更改时,Table View列列表的Change. wasPermanted()总是返回假

为什么如果数组列表中有重复项,我的代码SOMETIMES不返回true?

CSS应用于一个端点,但不应用于Thymeleaf中的另一个端点

@org.springframework.beans.factory.annotation.Autowired(required=true)-注入点有以下注释:-SpringBoot

Junit with Mockito for java

Java inline Double条件和值解装箱崩溃

查找剩余的枚举

带错误BER验证的itext8签名返回pdf

如何在Cosmos DB(Java SDK)中增加默认响应大小

有效的公式或值列表必须少于或等于255个字符

Lombok@Nonnull是否也对供应商有影响?

如何在太阳系模拟器中添加月球?

将关闭拍卖的TimerService

X=x*0.90;产生有损转换误差.X*=0.90;不是.为什么?

如何在Spring Boot中为不同的部署环境管理多个.properties文件?

验证没有';t work on Hibernate Entity';s字段