[英]@NotNull constraint don't work for a application property value spring boot
I want to prevent a NotNull value of a application property.我想阻止应用程序属性的 NotNull 值。
In my application.yml在我的 application.yml
spring:
security:
oauth2:
resourceserver:
my-property: classpath:a/b.json
my Property class:我的财产 class:
@Data
@Configuration
@ConfigurationProperties("spring.security.oauth2.resourceserver")
public class ABCProperties {
@NotNull
private URI myProperty
When the value of application property is empty, i don't have a constraint violation exception.当应用程序属性的值为空时,我没有约束违反异常。
How can i prevent that the value of application property is null?如何防止应用程序属性的值为 null?
You need to add @Validate
to your ABCProperties
as follows:您需要将
@Validate
添加到您的ABCProperties
,如下所示:
@Data
@Validated
@Configuration
@ConfigurationProperties("spring.security.oauth2.resourceserver")
public class ABCProperties {
@NotNull
private URI myProperty;
}
As a side note, as of Spring Boot 2.2, Spring finds and registers @ConfigurationProperties
classes via classpath scanning.附带说明一下,从 Spring Boot 2.2 开始,Spring 通过类路径扫描找到并注册
@ConfigurationProperties
类。 As a consequence, you do not need to annotate such classes with @Component
or @Configuration
or even use @EnableConfigurationProperties
.因此,您不需要使用
@Component
或@Configuration
注释此类类,甚至不需要使用@EnableConfigurationProperties
。 If you are using a Spring Boot version that is newer than 2.2 you can remove @Configuration
from your ABCProperties
class.如果您使用的是高于 2.2 的 Spring 引导版本,您可以从
ABCProperties
class 中删除@Configuration
。
When you have nested objects which fields must be validated, you need add @Valid
to that nested object class member declaration:当您有嵌套的对象时,必须验证哪些字段,您需要将
@Valid
添加到该嵌套的 object class 成员声明中:
@Data
@Validated
@Configuration
@ConfigurationProperties("spring.security.oauth2.resourceserver")
public class ABCProperties {
@Valid
private MyComplicatedProps myProperty;
@Data
public static class MyComplicatedProps {
@NotNull
private URI uri;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.