Home > Enterprise >  Java hibernate-validator @interface load from properties
Java hibernate-validator @interface load from properties

Time:11-30

I saw following hibernate validator code

package org.hibernate.validator.constraints;
...
public @interface CreditCardNumber {
   String message() default "{org.hibernate.validator.constraints.CreditCardNumber.message}";
...
}

and in the properties files has key value the credit card error message like

org.hibernate.validator.constraints.CreditCardNumber.message        = invalid credit card number

how do hibernate validator do such things
i mean load properties on @interface?

CodePudding user response:

As explained here Java Properties file examples you could use Properties class in your interface, with the method's default implementation as you already began.

public interface CreditCardNumber {
    Properties properties = new Properties();

    default String message() throws IOException {
        properties.load(Main.class.getClassLoader().getResourceAsStream("config.properties"));
        return properties.getProperty("org.hibernate.validator.constraints.CreditCardNumber.message");
    };
}

Or even a neater solution would be to create your own custom(a wrapper solution would be fine) Properties class, where you would load the properties file in its constructor (during construction). So you don't have to call properties.load(...) whenever you need it.

CodePudding user response:

To be clear - Hibernate Validator does not load the properties into an annotation. The annotation only references the key from the property file. Getting values out is part of interpolating constraint error messages. This process is a bit more complex than just reading a file, it has to deal with internationalization and interpolation.

As for the actual reading of the property files, in this case, it's done through ResourceBundles that underneath is using Properties class to load the data.

  • Related