Spring_ENUM_列挙タイプの注入
3390 ワード
Spring_ENUM_列挙タイプの注入
例は次のとおりです.
Gender.java
Worker.java
テスト:
テスト結果:
MALE
FEMALE
{FEMALE=110, MALE=111, UNSPECIFIED=112}
=====================END=====================
例は次のとおりです.
<?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=====================