【问题标题】:Inject Dependency Value Into Enum [duplicate]将依赖值注入枚举[重复]
【发布时间】:2015-11-24 18:42:18
【问题描述】:

我有以下枚举:

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;
        }
    }    
}

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

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,我将无法执行依赖注入(据我所知)。

让这些字符串在外部可配置和注入的最佳方法是什么?

【问题讨论】:

    标签: java dependency-injection enums spring-boot


    【解决方案1】:

    可能这个人有答案: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(...);
    }
    

    【讨论】:

      【解决方案2】:

      你做不到。但是你可以:

      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());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-09
        • 2013-04-25
        • 2012-08-31
        • 2016-03-05
        • 2017-11-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多