Spring Boot绑定@Value到Enum不区分大小写 [英] Spring Boot bind @Value to Enum case insensitive

查看:2444
本文介绍了Spring Boot绑定@Value到Enum不区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

枚举

public enum Property {
    A,
    AB,
    ABC;
}

字段

@Value("${custom.property}")
protected Property property;

application.properties (小写)

custom.property=abc

当我运行应用程序时出现错误:

When I'm running application I have an error:


无法将[java.lang.String]类型的值转换为必需类型
[com.xxx.Property]:找不到匹配的编辑或转换
策略。

Cannot convert value of type [java.lang.String] to required type [com.xxx.Property]: no matching editors or conversion strategy found.

然而(大写) ):

custom.property=ABC

工作正常。

有没有办法绑定不区分大小写的值?像 ABC Abc AbC abc 任何模式都应该有效。

Is there a way to bind the value case insensitive? Like ABC, Abc, AbC, abc any pattern should work.

注意:我看到了这个问题 - Spring 3.0 MVC绑定枚举区域敏感但在我的情况下,我有超过10个枚举/值(并期望有更多)类和实现10个不同的自定义属性绑定将是痛苦的,我需要一些通用的解决方案。

NOTE: I saw this question - Spring 3.0 MVC binding Enums Case Sensitive but in my case I have over 10 enums/values (and expect to have more) classes and to implement 10 different custom property binders would be painful, I need some generic solution.

推荐答案

@Value @ConfigurationProperties 功能不匹配。我无法强调 @ConfigurationProperties 是如何优越的。

@Value and @ConfigurationProperties features do not match. I couldn't stress enough how @ConfigurationProperties is superior.

首先,你可以在一个简单的POJO中设计你的配置,你可以在任何你想要的地方注入(而不是在注释中有表达式,你很容易打破一个错字) 。其次,元数据支持意味着您可以非常容易 在IDE中为自己的密钥获取自动完成功能

First, you get to design your configuration in a simple POJO that you can inject wherever you want (rather than having expressions in annotation that you can easily break with a typo). Second, the meta-data support means that you can very easily get auto-completion in your IDE for your own keys.

最后,轻松绑定描述在doc中仅适用于 @ConfigurationProperties @Value 是一个Spring Framework功能,并不知道轻松绑定。我们打算在文档中更明确地说明这一点

And finally, the relaxed binding described in the doc only applies to @ConfigurationProperties. @Value is a Spring Framework feature and is unaware of relaxed binding. We intend to make that more clear in the doc.

TL; DR abc 适用于 @ConfigurationProperties 但不适用于 @Value

TL;DR abc works with @ConfigurationProperties but won't with @Value.

这篇关于Spring Boot绑定@Value到Enum不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆