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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:20:19  来源:igfitidea点击:

Converting configuration properties to enum values

javaspringenums

提问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");