Java RestController REST parameter dependency injection or request

為{幸葍}努か 提交于 2021-02-11 17:19:25

问题


I am trying inject a dependency or at least filtrate the ID parameter that come into a RestControler in Spring. I am very new in Spring. How can i be sure that the parameter that comes passed in the API is valid and/or how can i inject its dependency related to Customer Entity?

This is my rest controller CustomerController method

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

This is the request that at the moment filtrates only the firstname and last name

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;
    }


}

Thank you!


回答1:


You need the Bean Validation API (which you probably already have) and it's reference implementation (e.g. hibernate-validator). Check here Java Bean Validation Basics

Summarizing

  1. Add the respective dependencies to your pom.xml (or 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. Use @Valid annotation on your Customer entity to have the payload validated automatically:
@PatchMapping("/{id}")
public Customer updateCustomer(@PathVariable Long id, @RequestBody @Valid Customer customer) {
  return customerService.updateCustomer(id, customer);
}
  1. You can decorate the fields of your Customer or CreateCustomerRequest class with further annotations, e.g. @Size, @Max, @Email etc. Check the tutorial for more information.


来源:https://stackoverflow.com/questions/60747846/java-restcontroller-rest-parameter-dependency-injection-or-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!