0

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!

Luiz Wynne
  • 460
  • 3
  • 10
  • 28

1 Answers1

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.
Kenan Güler
  • 1,868
  • 5
  • 16
  • 1
    you don't have to manually add these dependencies as they come with the `spring-boot-starter-web` which includes `spring-boot-starter-validation` by default – rieckpil Mar 20 '20 at 05:23