Spring_ENUM_枚举类型的注入

Spring_ENUM_枚举类型的注入


示例如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<bean id="worker" class="com.lyx.batch3.Worker">
		<property name="name" value="lyx" />
		<property name="age" value="12" />
		<!-- 枚举类型的注入 -->
		<property name="gender" value="MALE" />
	</bean>

	<bean id="worker1" class="com.lyx.batch3.Worker">
		<property name="name" value="lyx" />
		<property name="age" value="12" />
		<!-- 枚举类型的注入 定义常量字段 -->
		<property name="gender" ref="gender" />
	</bean>

	<!-- 必须是全限定名 -->
	<util:constant id="gender" static-field="com.lyx.batch3.Gender.FEMALE" />

	<!-- 枚举作为key注入 -->
	<util:map id="map" key-type="com.lyx.batch3.Gender">
		<entry key="FEMALE" value="110"/>
		<entry key="MALE" value="111" />
		<entry key="UNSPECIFIED" value="112" />
	</util:map>
</beans>

Gender.java

package com.lyx.batch3;

public enum Gender {
	MALE, FEMALE, UNSPECIFIED
}

Worker.java

package com.lyx.batch3;

public class Worker {
	private String name;
	private int age;
	private Gender gender;

	public Gender getGender() {
		return this.gender;
	}

	public void setGender(Gender gender) {
		this.gender = gender;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return this.age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}


测试:

package com.lyx.batch;

import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lyx.batch3.Gender;
import com.lyx.batch3.Worker;

public class TestInjectEnum {
	public static void main(String args[]) {
		@SuppressWarnings("resource")
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "classpath:spring-enum.xml" });

		Worker worker = (Worker) context.getBean("worker");
		System.out.println(worker.getGender().toString());

		Worker worker1 = (Worker) context.getBean("worker1");
		System.out.println(worker1.getGender().toString());

		Map<Gender, Object> hello = (Map<Gender, Object>) context
				.getBean("map");
		System.out.println(hello.toString());

	}
}


测试结果:

MALE

FEMALE

{FEMALE=110, MALE=111, UNSPECIFIED=112}


=====================END=====================


你可能感兴趣的:(Spring_ENUM_枚举类型的注入)