我有以下枚举:
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;
}
}
我想使用
someNumber
文件为枚举的两个实例设置不同的 application.properties
变量。
这可能吗?如果不可能,我应该使用抽象类/接口进行抽象,将其分成两个类吗?
那么您可以执行以下操作:
创建一个新类:MyEnumProperties
@ConfigurationProperties(prefix = "enumProperties")
@Getter
public class MyEnumProperties {
private Map<String, Long> enumMapping;
}
通过
为您的 SpringBootApplication/任何 Spring 配置启用 ConfigurationProperties@EnableConfigurationProperties(value = MyEnumProperties.class)
现在将您的号码添加到 application.properties 文件中,如下所示:
enumProperties.enumMapping.NAME=123
enumProperties.enumMapping.FAME=456
在您的应用程序代码中自动装配您的属性,如下所示:
@Autowired
private MyEnumProperties properties;
现在这是获取 id 的一种方法:
properties.getEnumMapping().get(MyEnum.NAME.name()); //should return 123
您可以通过这种方式为每个枚举值获取
application.properties
中定义的值
您不能/不应该更改 Java 中枚举的值。尝试使用类来代替:
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
}
创建自定义 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
}
现在您可以更改 application.properties 文件中
my.config.name.someNumber
和 my.config.fame.someNumber
的值。如果您想禁止更改小写/态度,请将其作为最终的。
在使用它之前,您必须使用
@Configuration
注释
@EnableConfigurationProperties(MyConfigConfigurationProperties.class)
类。还要添加 org.springframework.boot:spring-boot-configuration-processor
作为可选依赖项以获得更好的 IDE 支持。
如果您想访问这些值:
@Autowired
MyConfigConfigurationProperties config;
...
config.getName().getSumeNumber();