本文介绍了使用 Spring IoC 设置枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在构建时通过 Spring IoC 设置这样的枚举值?

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 in the code snippet below:

public enum Car
{
        NANO ("Very Cheap", "India"),
        MERCEDES ("Expensive", "Germany"),
        FERRARI ("Very Expensive", "Italy");

        public final String cost;
        public final String madeIn;

        Car(String cost, String madeIn)
        {
                this.cost= cost;
                this.madeIn= madeIn;
        }

}

假设应用程序必须部署在德国,在那里 Nanos几乎免费",或者在法拉利负担不起"的印度.在这两个国家,只有三辆车(确定性集合),不多也不少,因此是一个枚举,但它们的内部"值可能不同.所以,这是一个不可变的上下文初始化的情况.

Let's say that the application must be deployed in Germany, where Nanos are "Nearly free", or in India where Ferraris are "Unaffordable". In both countries, there are only three cars (deterministic set), no more no less, hence an enum, but their "inner" values may differ. So, this is a case of contextual initialization of immutables.

推荐答案

你的意思是设置 enum 本身吗?

Do you mean setting up the enum itself?

我认为这不可能.您不能实例化枚举,因为它们具有 static 性质.所以我认为 Spring IoC 也不能create enums.

I don't think that's possible. You cannot instantiate enums because they have a static nature. So I think that Spring IoC can't create enums as well.

另一方面,如果您需要使用 enum 设置初始化内容,请查看 Spring IoC 章节.(搜索枚举)有一个简单的例子,你可以使用.

On the other hand, if you need to set initialize something with a enum please check out the Spring IoC chapter. (search for enum) There's a simple example that you can use.

这篇关于使用 Spring IoC 设置枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 18:45