javax验证api无法用于pojo验证 [英] javax validation api not working for pojo validation

查看:100
本文介绍了javax验证api无法用于pojo验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个POJO类,其中的类变量通过@Value注释注入.我正在尝试使用javax验证api&来验证我的类变量.因此,我尝试了@NotNull@NotEmpty@NotBlank,但是即使在application.yml文件中存在空白/空值时,它们似乎都无法验证或引发任何形式的异常.关于如何在此处使用javax验证api验证POJO的任何想法? PS:我正在使用lombok来生成我的getter/setter.

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.

下面是我的示例代码!

POJO类:

@Component
@Getter
@Setter
public class Credentials {

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

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

}

下面是application.yml文件:

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.

推荐答案

我认为可以应用. >

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);

    }
}

这篇关于javax验证api无法用于pojo验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆