问题
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
- 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>
- Use
@Valid
annotation on yourCustomer
entity to have the payload validated automatically:
@PatchMapping("/{id}")
public Customer updateCustomer(@PathVariable Long id, @RequestBody @Valid Customer customer) {
return customerService.updateCustomer(id, customer);
}
- You can decorate the fields of your
Customer
orCreateCustomerRequest
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