1

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

VioletTec
  • 71
  • 5

1 Answers1

0

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

Cheatr01
  • 51
  • 5
  • But why I added the `@Configuration` to my Person class which used `@PropertySource`, It still didn't work. – VioletTec Feb 13 '23 at 03:30
  • For using PropertySource you must use *.properties configuration file. PropertySource doesn't read yamls. – Cheatr01 Mar 04 '23 at 22:07