2016-09-14 94 views
-1

我正在尋找如何在Spring中注入Map<Integer, CustomEnumType>,而不是使用app-context.xml,而是使用@Bean(name = "customMap")註釋。當我嘗試做在Spring中使用Enum注入映射值

@Inject 
Map<Integer, CustomEnumType> customMap; 

注入它,它抱怨,因爲顯然它無法找到CustomEnumType類型的任何可注射的依賴性。但CustomEnumType只是一個枚舉,而不是應該被注入的東西。我只是想用它作爲我的地圖的value類型。

一個解決方案是創建一個包含Map作爲字段的可注入包裝對象,但我想避免不必要的混亂。看到Map被注入的類型也更加乾淨和易讀。

+0

問題格式不正確?有人不明白我在問什麼? – Konstantine

回答

0

我找到了解決辦法。顯然@Inject@Autowired未能正確找到他們需要使用的@Bean方法的類型。但是,使用@Resource(name = "customMap")一切都很完美。即使值是枚舉,地圖創建也沒有問題。使用的方法是:

@Bean(name = "customMap") 
public Map<Integer, CustomEnumType> getCustomMap() { 
    Map<Integer, CustomEnumType> map = new HashMap<>(); 
    map.put(1, CustomEnumType.type1); 
    map.put(2, CustomEnumType.type2); 
    //... 
    return map; 
} 

和使用

@Resource(name = "customMap") 
Map<Integer, CustomEnumType> customMap; 

注意CustomEnumType沒有定義的構造和沒有值被分配給枚舉注入。在我的情況下,從一開始這也是不可能的,因爲CustomEnumType類是我們無法編輯的依賴項。

0

不要嘗試注入枚舉,而是嘗試注入int值。

枚舉確實是類,但是,您不能創建它們的實例/對象。他們的構造函數訪問修飾符只能是private,這是另一個證明你爲什麼不能擁有它們的實例。

說到這裏,你不能擁有Enum Bean,因爲沒有辦法構建它們。

解決的辦法是給你的枚舉中的每個成員,一個int值,並只是注入該int值。

例如:

public enum Color { 
    white(0), 
    black(1); 

    private int innerValue; 

    private Color(int innerValue) { 
     this.innerValue = innerValue; 
    } 

    public int getInnerValue() { 
     return innerValue; 
    } 
} 

現在,讓我們說,我要注入的值爲1,這是黑在我的枚舉。通過其構造器到另一個類。然後我的構造函數將是這樣的:

public Canvas(String id, int color) { 
    this.id = id; 
    this.color = Color.getColorByInt(color); 
} 

現在,讓我們說,這包含XML配置文件:

<bean id="myCanvas" class="com.my.package.Canvas"> 
<constructor-arg name="id" value="9876543" /> 
<constructor-arg name="color" value="1" /> 
<!-- This is the black value for myCanvas bean --> 
</bean>