Search code examples
javaspringvalidationannotations

How to make simple property validation when using Spring @Value


How can I check, if ${service.property} is not an empty string and if so, throw some kind of readable exception? It must happen during Bean creation.

@Component
public class Service {

  @Value("${service.property}")
  private String property;
}

I am looking for the easiest way (least written code). Would be great if by using annotations.

My current solution is to perform "handwritten" validation inside setter for the property, but is a little too much code for such easy thing.

Hint: I looked for some way to use the SpEL, since I use it already inside @Value, but as far I have found out, it would not be that easy/clean. But could have overlooked something.

Clarification: Expected behaviour is, that the application will not start up. The goal is to assure, that all properties are set, and especially, that string properties are not empty. Error should say clearily, what is missing. I don't want to set any defaults! User must set it all.


Solution

  • You can use the component as a property placeholder itself. And then you may use any validation that you want.

    @Component
    @Validated
    @PropertySource("classpath:my.properties")
    @ConfigurationProperties(prefix = "my")
    public class MyService {
    
        @NotBlank
        private String username;
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        ...
    }
    

    And your my.properties file will look like this:

    my.username=felipe