package com.cgy.springrecipes.sequence;
import java.text.DecimalFormat;
import java.util.List;
public class SequenceGenerator {
private PrefixGenerator prefixGenerator; //PrefixGenerator类代码在前面博客
private List<Object> suffixes;
private int initial;
private int counter;
public SequenceGenerator() {}
public SequenceGenerator(PrefixGenerator prefixGenerator) {
this.prefixGenerator = prefixGenerator;
}
public void setPrefixGenerator(PrefixGenerator prefixGenerator) {
this.prefixGenerator = prefixGenerator;
}
public void setSuffixes(List<Object> suffixes) {
this.suffixes = suffixes;
}
public void setInitial(int initial) {
this.initial = initial;
}
public synchronized String getSequence() {
StringBuffer buffer = new StringBuffer();
buffer.append(prefixGenerator.getPrefix());
buffer.append(initial + counter++);
DecimalFormat formatter = new DecimalFormat("0000");
for(Object suffix : suffixes) {
buffer.append("-");
buffer.append(formatter.format( (Integer)suffix) );
}
return buffer.toString();
}
}
运行发现,黄色高亮的代码行报错,java.lang.ClassCastException,其原因是Bean配置文件中,默认集合元素的类型都是String,因此当试图转为Integer时失败,此时正需要指定元素类型。<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="sequenceGenerator" class="com.cgy.springrecipes.sequence.SequenceGenerator">
<constructor-arg>
<bean class="com.cgy.springrecipes.sequence.DatePrefixGenerator">
<property name="pattern" value="yyyyMMdd"/>
</bean>
</constructor-arg>
<property name="suffixes">
<list>
<value>5</value>
<value>10</value>
<value>20</value>
</list>
</property>
<property name="initial" value="10000"/>
</bean>
</beans>
使用<value>标记的type属性指定元素类型为int,运行成功,输出:<property name="suffixes">
<list>
<value type="int">5</value>
<value type="int">10</value>
<value type="int">20</value>
</list>
</property>
或者使用在集合标记中使用value-type指定所有元素的数据类型达到同样效果
<property name="suffixes">
<list value-type="int">
<value>5</value>
<value>10</value>
<value>20</value>
</list>
</property>
在Java1.5以及更高的的版本上,可以用存储整数的类型安全集合定义suffixes
Spring将通过反射读取集合的类型信息,不再需要指定集合标记中的<value-type>属性。private List<Integer> suffixes;