3

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
zbstof
  • 1,052
  • 3
  • 14
  • 27
  • As an option, you can annotate setters of these fields (instead of direct annotating the fields) and make the all validation in these setters. Then you can throw an error in case if validation fails. – Roman Proshin Jun 06 '17 at 14:50
  • @RomanProshin: setting validation on setters doesn't work, I'm getting an exception: Cross parameter constraint X has no cross-parameter validator. Validation on methods is performed on return value, which is 'void' for settters – zbstof Jun 06 '17 at 15:46
  • 1
    Validation will only work for `@ConfigurationProperties` annotated classes combined with using `@EnableConfigurationProperties`. – M. Deinum Jun 06 '17 at 18:25
  • Hi, @M.Deinum, this sounds like what is happening, but could you please add the explanation why is that so as in an answer, if that is not too much trouble? Thank you. – zbstof Jun 07 '17 at 08:29
  • I already answered that: https://stackoverflow.com/questions/44007492/spring-value-annotation-enforce-min-max-int/44021485#44021485 – M. Deinum Jun 07 '17 at 13:23

1 Answers1

1

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>
MaQuiNa1995
  • 431
  • 1
  • 9
  • 23