Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting configuration properties to enum values

Tags:

java

enums

spring

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

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?

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.

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?
like image 491
thg Avatar asked Oct 30 '13 09:10

thg


2 Answers

Spring automatically converts input Strings to the corresponding valueOf of the desired enum.

like image 92
thg Avatar answered Oct 14 '22 02:10

thg


You can do that by

LoginMode.valueOf("someString");
like image 33
Eel Lee Avatar answered Oct 14 '22 01:10

Eel Lee