I have a simple method to get a list of documents for a given companyId
. Here is the method:
@Override
public List<Documents> getDocumentList(@NotNull Integer companyId) {
Company company = new Company(companyId);
return this.documentRepository.findByCompany(company);
}
I wanted to use Javax validation constraints to ensure that the companyId
being passed in, is not null
. But it seems to not have any effect, as I'm able to pass in a null
value, and it flows down to the findByCompany
call on the repository. I also added @Valid
before @NotNull
to force validation, but that too didn't do anything.
I could always write a couple of lines to check for a null
value, but wanted to use javax.validation
annotations to make the code more readable and concise. Is there a way to make the annotations work on method params?
要激活参数验证,只需使用@Validated
注释该类
import org.springframework.validation.annotation.Validated;
From The Java EE 6 Tutorial:
The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component , such as a managed bean .
You should place your validation of a field related to a declared bean, something like this:
@Entity
@Table(name="users")
public class BackgammonUser {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long userId;
@Column(name="username")
@NotBlank
private String userName;
@NotBlank
private String password;
@NotNull
private Boolean enabled;
}
The BackgammonUser is considered to be a bean.
If you @Inject
a class with your method, its working as expected.
@Stateless
public class MyBean{
@Inject
TestClass test;
}
and
public class TestClass {
public List<Documents> getDocumentList(@NotNull Integer companyId)
{
//...
}
}
ConstraintViolationException
when you call your method with null parameter:
WFLYEJB0034: EJB Invocation failed on component MyBean for method ...:
javax.ejb.EJBException: javax.validation.ConstraintViolationException:
1 constraint violation(s) occurred during method validation.
@NotNull Annotation,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.