【问题标题】:Java RestController REST parameter dependency injection or requestJava RestController REST 参数依赖注入或请求
【发布时间】:2020-03-18 21:38:56
【问题描述】:

我正在尝试注入依赖项或至少过滤进入 Spring 中的 RestControler 的 ID 参数。我在春天很新。我如何确定传入 API 的参数是有效的和/或如何注入与客户实体相关的依赖项?

这是我的休息控制器 CustomerController 方法

@PatchMapping("/{id}")
    public Customer updateCustomer(@PathVariable Long id, @RequestBody Customer customer) {
        return customerService.updateCustomer(id, customer);
    }

这是目前仅过滤名字和姓氏的请求

package com.appsdeveloperblock.app.ws.requests.customer;
import javax.validation.constraints.NotNull;

public class CreateCustomerRequest {


    @NotNull
    private String firstname;

    @NotNull
    private String lastname;

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }


}

谢谢!

【问题讨论】:

    标签: java spring-boot spring-restcontroller


    【解决方案1】:

    您需要 Bean Validation API(您可能已经拥有)和它的参考实现(例如 hibernate-validator)。在这里查看Java Bean Validation Basics

    总结

    1. 将各自的依赖项添加到您的 pom.xml(或 gradle)中:
    <dependencies>
      <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>2.0.1.Final</version>
      </dependency>
    
      <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.1.2.Final</version>
      </dependency>
    
      <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator-annotation-processor</artifactId>
        <version>6.1.2.Final</version>
      </dependency>
    </dependencies>
    
    1. 在您的 Customer 实体上使用 @Valid 注释以自动验证有效负载:
    @PatchMapping("/{id}")
    public Customer updateCustomer(@PathVariable Long id, @RequestBody @Valid Customer customer) {
      return customerService.updateCustomer(id, customer);
    }
    
    1. 您可以使用更多注释来装饰Customer 或CreateCustomerRequest 类的字段,例如@Size、@Max、@Email 等。查看教程了解更多信息。

    【讨论】:

    • 您不必手动添加这些依赖项,因为它们与 spring-boot-starter-web 一起提供,默认情况下包括 spring-boot-starter-validation
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2016-01-26
    • 1970-01-01
    相关资源
    最近更新 更多