8

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?
thg
  • 1,209
  • 1
  • 14
  • 26
  • possible duplicate of [Java - Convert String to enum](http://stackoverflow.com/questions/604424/java-convert-string-to-enum) – Eel Lee Oct 30 '13 at 09:42
  • it is not a duplicate of that question, see edit. – thg Oct 30 '13 at 10:00
  • 1
    so maybe that http://stackoverflow.com/questions/13030974/spring-how-do-i-inject-enum-in-spring-configuration will help? – Eel Lee Oct 30 '13 at 10:01
  • thanks for the suggestion but the answer was quite simple... ill post it – thg Oct 30 '13 at 10:11

3 Answers3

22

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

thg
  • 1,209
  • 1
  • 14
  • 26
3

You can do that by

LoginMode.valueOf("someString");
Eel Lee
  • 3,513
  • 2
  • 31
  • 49
2
 LoginMode.valueOf(valueOfProperty);

EDIT: Try using converter 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?

Community
  • 1
  • 1
smajlo
  • 972
  • 10
  • 21
  • where would i have to convert the string? in the bean configuration or in the environment class? – thg Oct 30 '13 at 09:47