Reputation: 1158
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?
Upvotes: 11
Views: 29443
Reputation: 41
You can't/shouldn't change values of a enum in Java. Try using a class instead:
public class MyCustomProperty {
// can't change this in application.properties
private final String lowerCase;
// can change this in application.properties
private String atitude;
private long someNumber;
public MyCustomProperty (String lowerCase, String atitude, long someNumber) {
this.lowerCase = lowerCase;
this.atitude = atitude;
this.someNumber = someNumber;
}
// getter and Setters
}
Than create a custom ConfigurationProperties:
@ConfigurationProperties(prefix="my.config")
public class MyConfigConfigurationProperties {
MyCustomProperty name = new MyCustomProperty("name", "good", 100);
MyCustomProperty fame = new MyCustomProperty("fame", "good", 100);
// getter and Setters
// You can also embed the class MyCustomProperty here as a static class.
// For details/example look at the linked SpringBoot Documentation
}
Now you can change the values of my.config.name.someNumber
and my.config.fame.someNumber
in the application.properties file. If you want to disallow the change of lowercase/atitude make them final.
Before you can use it you have to annotate a @Configuration
class with @EnableConfigurationProperties(MyConfigConfigurationProperties.class)
. Also add the org.springframework.boot:spring-boot-configuration-processor
as an optional dependency for a better IDE Support.
If you want to access the values:
@Autowired
MyConfigConfigurationProperties config;
...
config.getName().getSumeNumber();
Upvotes: 4
Reputation: 4461
Well what you can do is the following:
Create a new class: MyEnumProperties
@ConfigurationProperties(prefix = "enumProperties")
@Getter
public class MyEnumProperties {
private Map<String, Long> enumMapping;
}
Enable ConfigurationProperties to your SpringBootApplication/ any Spring Config via
@EnableConfigurationProperties(value = MyEnumProperties.class)
Now add your numbers in application.properties file like this:
enumProperties.enumMapping.NAME=123
enumProperties.enumMapping.FAME=456
In your application code autowire your properties like this:
@Autowired
private MyEnumProperties properties;
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
Upvotes: 6