Jestino Sam
Jestino Sam

Reputation: 602

javax validation api not working for pojo validation

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.

Upvotes: 0

Views: 1693

Answers (2)

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

    }
}

Upvotes: 1

Mubin
Mubin

Reputation: 4239

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.

Upvotes: 1

Related Questions