Java 将配置属性转换为枚举值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19678664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting configuration properties to enum values
提问by thg
I have a configuration file which contains this line:
我有一个包含这一行的配置文件:
login.mode=PASSWORD
and an enum
和一个枚举
public enum LoginMode {
PASSWORD, NOT_PASSWORD, OTHER }
and a spring bean
和一个春豆
<bean id="environment" class="a.b.c.Environment" init-method="init">
<property name="loginMode" value="${login.mode}"/>
</bean>
and of course a bean class
当然还有一个bean类
public class Environment {
private LoginMode loginMode;
public LoginMode getLoginMode() {
return loginMode;
}
public void setLoginMode(LoginMode loginMode) {
this.loginMode = loginMode;
}
}
How can i convert the property of the configuration file (which is a String) into the corresponding enum value of LoginMode?
我如何将配置文件的属性(它是一个字符串)转换为 LoginMode 的相应枚举值?
EDIT: i know how to get the enum value of a string input, but the issue is another one: If i try this:
编辑:我知道如何获取字符串输入的枚举值,但问题是另一个:如果我尝试这个:
public class Environment {
private LoginMode loginMode;
public LoginMode getLoginMode() {
return loginMode;
}
public void setLoginMode(String loginMode) {
this.loginMode = LoginMode.valueOf(loginMode);
}
}
spring is complaining about getter and setter not having the same input and output type.
spring 抱怨 getter 和 setter 没有相同的输入和输出类型。
Bean property 'loginMode' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
采纳答案by thg
Spring automatically converts input Strings to the corresponding valueOf of the desired enum.
Spring 自动将输入字符串转换为所需枚举的相应 valueOf。
回答by Eel Lee
You can do that by
你可以这样做
LoginMode.valueOf("someString");
回答by smajlo
LoginMode.valueOf(valueOfProperty);
EDIT: Try using converter http://docs.spring.io/spring/docs/3.0.0.RC2/reference/html/ch05s05.htmlhttp://forum.spring.io/forum/spring-projects/web/83191-custom-enum-string-converters
编辑:尝试使用转换器 http://docs.spring.io/spring/docs/3.0.0.RC2/reference/html/ch05s05.html http://forum.spring.io/forum/spring-projects/web/ 83191-custom-enum-string-converters
EDIT2: also check this: How assign bean's property an Enum value in Spring config file?
EDIT2: 还要检查这个: How assign bean's property an Enum value in Spring config file?