限制application.properties中的可能值

时间:2019-08-23 13:56:06

标签: java spring spring-boot spring-mvc

我想限制 application.properties 的可能值,例如

condition =”表示“ YES ”和“ NO *” **,后来是 YES / NO 为{{1 }}, 但我收到“无法将类型'enum'的值转换为必需的类型”。

我该如何实现?

java.lang.String

3 个答案:

答案 0 :(得分:3)

  

创建一个新类: MyNewEnumProperties

@ConfigurationProperties(prefix = "enumProperties")
@Getter
public class MyNewEnumProperties{

    private Map<String, Long> enumMapping;

}
  

为您的SpringBootApplication /任何启用ConfigurationProperties   通过

@EnableConfigurationProperties(value = MyNewEnumProperties.class)
  

现在将您的东西添加到application.properties文件中,如下所示:

enumProperties.enumMapping.YES=1
enumProperties.enumMapping.NO=0
  

在您的应用程序代码中,按如下所示自动连接属性:

@Autowired
private MyNewEnumProperties properties;

reference

答案 1 :(得分:0)

属性值(在配置中)应与枚举值之一完全相同(也许您在“ NO”中有错字-多余的*)。

获取属性所需要做的就是这个:

@Value("${condition}")
private PossibleConditions condition;

请参见工作示例项目(非常轻松)here in github

如果application.properties中属性的值不完全是YESNO,那么您将收到解析错误,并且应用程序将无法启动(我猜是是你想要的)。

答案 2 :(得分:0)

您可以像这样扩展iterrows()

PropertyEditorSupport

然后,您可以将public class PossibleConditionsEditor extends PropertyEditorSupport { public void setAsText(final String text) throws IllegalArgumentException { switch (text) { case "YES": setValue(PossibleConditions.YES); break; case "NO": setValue(PossibleConditions.NO); break; default: throw new IllegalArgumentException("Possible values are YES and NO"); } } } 与属性名称一起使用,以注入@Value()的值。

PossibleConditions