Using Spring IoC to set up enum values

后端 未结 13 1785
名媛妹妹
名媛妹妹 2020-11-30 06:06

Is there a way to set up such enum values via Spring IoC at construction time?

What I would like to do is to inject, at class load time, values that are hard-coded i

相关标签:
13条回答
  • 2020-11-30 06:34

    I don't think it can be done from Spring's ApplicationContext configuration. But, do you really need it done by Spring, or can you settle for simple externalization using ResourceBundle; like this:

    public enum Car
    {
        NANO,
        MERCEDES,
        FERRARI;
    
        public final String cost;
        public final String madeIn;
    
        Car()
        {
                this.cost = BUNDLE.getString("Car." + name() + ".cost");
                this.madeIn = BUNDLE.getString("Car." + name() + ".madeIn");
        }
    
        private static final ResourceBundle BUNDLE = ResourceBundle.getBundle(...);
    
    }
    

    In the properties file, one for each specific locale, enter the keys describing the possible internal enum values:

    Car.NANO.cost=Very cheap
    Car.NANO.madeIn=India
    Car.MERCEDES.cost=Expensive
    ...
    

    The only drawback of this approach is having to repeat the name of enum fields (cost, madeIn) in Java code as strings. Edit: And on the plus side, you can stack all properties of all enums into one properties file per language/locale.

    0 讨论(0)
提交回复
热议问题