Why SpringBoot validation not work with single @PropertySource

88 Views Asked by At

My Source code:

Person.java

@Component
@Validated
@PropertySource(value = "classpath:person.yaml")

@Data
public class Person {
    @NotNull(message = "test can't be null")
    private String test;
    @Value("${name}")
    private String name;
    @Autowired
    private Cat pet;
    @Max(value=120,message="invalid age")
    @Value("${age}")
    private int age;

    @Email(message = "invalid email address")
    @Value("${email}")
    private String email;
}

person.yaml

name: "test"
email: "abcdefg"
age: 11111

I use my Person class on SpringBootApplication with invalid email address and age, but it ran successfully without any validation exception.

imagef8e160a66fd93d78.png

But If I replace the @PropertySource(value = "classpath:person.yaml") to @ConfigurationProperties(prefix = "person") or use both @PropertySource and @ConfigurationProperties

application.yaml

person:
  name: "test"
  email: "abcdefg"
  age: 11111

My SpringBoot throw an validation exception successfully. image.png

1

There are 1 best solutions below

2
On

From @PropertySource documantation:

Annotation providing a convenient and declarative mechanism for adding a PropertySource to Spring's Environment. To be used in conjunction with @Configuration classes.

You don't have @Configuration anotation under class declaration.

Your second example has @ConfigurationProperties annotation and this is from documentation:

Annotation for externalized configuration. Add this to a class definition or a @Bean method in a @Configuration class if you want to bind and validate some external Properties (e.g. from a .properties file).

In a nutshell: @PropertySource need @Configuration but @ConfigurationProperties not.

EDIT: Last not first visible detail: PropertySource cannot read yaml files :-)