Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 992
Tomasz Avatar asked Apr 22 '15 12:04

Tomasz


People also ask

How do you validate an object in spring boot?

Instead, we can let Spring know that we want to have a certain object validated. This works by using the the @Validated and @Valid annotations. The @Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class.

How do you validate the range of a number in Spring?

In Spring MVC Validation, we can validate the user's input within a number range. The following annotations are used to achieve number validation: @Min annotation - It is required to pass an integer value with @Min annotation. The user input must be equal to or greater than this value.


1 Answers

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
like image 188
Felipe Desiderati Avatar answered Oct 04 '22 15:10

Felipe Desiderati