Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Spring 如何注入列舉型別物件

一、列舉

實際開發中常出現這樣的「資料集」:數值在程式執行期間穩定,而且元素數量有限。例如星期一至星期日構成一週的資料集,春夏秋冬構成四季的資料集。Java 中要更好地表達這類集合,列舉就派上用場了:

public enum ColorEnum { RED, GREEN, YELLOW, BLUE; }

二、在 Spring 中注入列舉

先定義列舉型別:

package com.zcr.util;
public enum ColorEnum {
    RED, GREEN, YELLOW, BLUE;
}

再寫一個持有該列舉的類別:

package com.zcr.util;
// 使用列舉型別
public class Car {
    private ColorEnum colorEnum;
}

接著在 Spring 組態檔中加入:

<!-- 注入列舉 -->
<bean id="red" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
    <property name="staticField" value="com.zcr.util.ColorEnum.RED" />
</bean>
<bean id="car" class="com.zcr.util.Car">
    <property name="colorEnum" ref="red" />
</bean>

關鍵點:列舉要注入到類別中,必須先用 org.springframework.beans.factory.config.FieldRetrievingFactoryBean 做轉換,也就是把 ColorEnum.RED 變成一個名為 red 的 bean,再由要注入的 bean 以 <property name="colorEnum" ref="red" /> 引用。

使用端加上:

@Autowired
private Car car;

三、注入 JDK 自帶的列舉

Java 本身就有很多列舉類,例如 java.util.concurrent.TimeUnit,其定義為 public enum TimeUnit extends Enum<TimeUnit>。要在 Spring 中取得它的實例,寫法完全一樣:

<bean id="timeUnit" class="org.springframework.beans.factory.config.FieldRetrievingFactoryBean">
    <property name="staticField" value="java.util.concurrent.TimeUnit.SECONDS" />
</bean>
@Autowired
private TimeUnit timeUnit;

四、為什麼要用組態檔的方式

TimeUnit 有毫秒、秒、分、時、天等多種單位,而專案通常會統一採用其中一種。寫在組態檔裡有助於解耦:要改單位時只需改一個地方,不必動程式碼;而且這個物件往往被多處使用,集中設定後一次修改就能全面生效,維護成本最低。

Copyright © Linux教程網 All Rights Reserved