Search code examples
javaspringspring-bootenums

Configuring an enum in Spring using application.properties


I have the following enum:

public enum MyEnum {
    NAME("Name", "Good", 100),
    FAME("Fame", "Bad", 200);

    private String lowerCase;
    private String atitude;
    private long someNumber;

    MyEnum(String lowerCase, String atitude, long someNumber) {
        this.lowerCase = lowerCase;
        this.atitude = atitude;
        this.someNumber = someNumber;
    }
}

I want to set up the someNumber variable differently for both instances of the enum using application.properties file.

Is this possible and if not, should I split it into two classes using an abstract class/interface for the abstraction?


Solution

  • Well what you can do is the following:

    1. Create a new class: MyEnumProperties

      @ConfigurationProperties(prefix = "enumProperties")
      @Getter
      public class MyEnumProperties {
      
          private Map<String, Long> enumMapping;
      
      }
      
    2. Enable ConfigurationProperties to your SpringBootApplication/ any Spring Config via

      @EnableConfigurationProperties(value = MyEnumProperties.class)
      
    3. Now add your numbers in application.properties file like this:

      enumProperties.enumMapping.NAME=123
      enumProperties.enumMapping.FAME=456
      
    4. In your application code autowire your properties like this:

      @Autowired
      private MyEnumProperties properties;
      
    5. Now here is one way to fetch the ids:

      properties.getEnumMapping().get(MyEnum.NAME.name()); //should return 123
      

    You can fetch this way for each Enum value the values defined in your application.properties