将依赖值注入Enum

时间:2015-11-24 18:42:19

标签: java dependency-injection enums spring-boot

我有以下枚举:

public class Wrapper(){
    public enum MyEnum{
        A("a_id", "a_source", "a_target"),
        B("b_id", "b_source", "b_target"),
        ...
        Z("z_id", "z_source", "z_target"),

        String id;
        String source;
        String target;
        myEnum(String i, String s, String t){
            id = i;
            source = s;
            target = t;
        }
    }    
}

如果可能,我希望能够在"a_id"中指定枚举参数(例如application.properties),以便我可以根据需要修改它们并将其注入。我最初想的是:

public class Wrapper(){
    @Value("${a.id}")
    private String A_ID;
    @Value("${a.source}")
    private String A_SOURCE;
    @Value("${a.target}")
    private String A_TARGET;

    public enum MyEnum{
        A(A_ID, A_SOURCE, A_TARGET),
        ...
    }    
}

application.properties看起来像:

a.id=a_id
a.source=a_source
a.target=a_target

问题是我无法在枚举中调用A_ID而不使其static但是如果我使它static我无法执行依赖注入(根据我的理解)。

将这些字符串外部配置并注入的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

可能这个人有答案:https://stackoverflow.com/a/711022/4546150

正如dnault所说,尝试从Spring获取application.properties的配置值 - 你需要保证Spring已经加载并解析了配置,然后尝试将其注入静态对象。

但是,正如我发布的SO帖子所提到的那样 - 你是否需要为此使用Springs配置加载?我相信Resource Bundle被提及作为替代方案:

public enum MyEnum {
A;

public final String id;
public final String source;
public final String target;

MyEnum() {
    this.id = BUNDLE.getString("A.id");
    this.source = BUNDLE.getString("A.source");
    this.target = BUNDLE.getString("A.target");
}

private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(...);
}

答案 1 :(得分:1)

你不能这样做。但你可以:

public enum MyEnum {
     A, B, C, .... Z;

     String idKey() { return name().toLowerCase() + ".id"; }
     String sourceKey() { return name().toLowerCase() + ".source"; }
     String targetKey() { return name().toLowerCase() + ".target"; }

};

然后你可以在你定义的属性文件中,然后在客户端代码中的某个地方:

MyEnum e = ...
properties.getProperty(e.idKey());