Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate @Value-annotated fields during application startup [duplicate]

How can I check that values in a property file conform to my expectations during application startup? Annotating fields directly doesn't work. I'm using spring boot 1.5.3.RELEASE, spring 4.3.8.RELEASE

Service:

@Service
@Validated
public class ConfigService {
    @URL
    @Value("${checkout.url}")
    private String checkoutUrl;
    @Size(max = 26)
    @Value("${checkout.payment-method}")
    private String paymentMethod;
}

Property file (application.properties):

checkout.url=not-a-url-at-all
checkout.payment-method=CreditCardButMuchTooLongToQualifyForSizeValidator
like image 639
zbstof Avatar asked Dec 04 '25 09:12

zbstof


1 Answers

You can use this getter methods style in your class for validate String length:

@Size(min = Number, max = Number)
public String getField() {
    return field;
}

and for validate numbers:

@Max(Number) or @Min(Number) 

When Number is equal to int value

if the fields dont have this limitations it will throw a java.lang.IllegalStateException

dont forget to add this dependency to your pom if you dont have:

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>el-impl</artifactId>
    <version>2.2</version>
</dependency>
like image 52
MaQuiNa1995 Avatar answered Dec 06 '25 21:12

MaQuiNa1995