javax validation api not working for pojo validation

牧云@^-^@ 提交于 2020-06-01 05:11:27

问题


I have a POJO class where the class variables are getting injected by @Value annotation. I am trying to validate my class variables using javax validation api & so I have tried @NotNull, @NotEmpty and @NotBlank, but all of them seem not to be validating or throwing any kind of exception even when a blank/null value is present in the application.yml file. Any idea as to how can I validate my POJO here using the javax validation api? PS: I am using lombok to generate my getter/setter.

Below is my sample code!

POJO Class:

@Component
@Getter
@Setter
public class Credentials {

    @NotBlank
    @Value("${app.username}")
    private String user_name;

    @NotBlank
    @Value("${app.password}")
    private String password;

}

Below is the application.yml file:

app:
    username: '#{null}'
    password: passWord

Even if I provide a blank value, I don't get any exception when I try to print these values in the console.


回答1:


I think this can be applied.

@Data
@RequiredArgsConstructor
public class Credentials {

    private final String user_name;

    private final String password;

}

 

@Configuration
@Validated
public class CredentialsConfiguration {

    @Bean
    public Credentials credentials(
        @NotBlank @Value("${app.username}") final String user_name,
        @NotBlank @Value("${app.password}") final String password) {

        return new Credentials(user_name, password);

    }
}



回答2:


Validation will only work for @ConfigurationProperties annotated classes combined with using @EnableConfigurationProperties.

The reason you don't get any exception is that @Value only looks for presence of the attribute in the properties, it doesn't care what the value of that attribute is, unless you are assigning a mis-matching datatype value.



来源:https://stackoverflow.com/questions/62091358/javax-validation-api-not-working-for-pojo-validation

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