<bean name="sequenceGenerator"
class="com.cgy.springrecipes.sequence.SequenceGenerator">
<property name="prefix">
<value>30</value>
</property>
<property name="suffix">
<value>A</value>
</property>
<property name="initial">
<value>1000000</value>
</property>
</bean>
package com.cgy.springrecipes.sequence;
public class SequenceGenerator {
private String prefix;
private String suffix;
private int initial;
private int counter;
public SequenceGenerator() {}
public SequenceGenerator(String prefix, String suffix, int initial) {
this.prefix = prefix;
this.suffix = suffix;
this.initial = initial;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public void setInitial(int initial) {
this.initial = initial;
}
public synchronized String getSequence() {
StringBuffer buffer = new StringBuffer();
buffer.append(prefix);
buffer.append(initial + counter++);
buffer.append(suffix);
return buffer.toString();
}
}
SequenceGenerator类中只有setter方法,没有getter方法,因此类中的属性都是通过配置文件中<property>元素来配置的,每一个<property>要求bean包含对应的一个设值方法(setter)。同时可以在<constructor-arg>元素中配置属性,但是没有name属性,因为该顺序基于构造函数参数的位置。
简写定义Bean属性
<bean name="sequenceGenerator" class="com.cgy.springrecipes.sequence.SequenceGenerator">
<property name="prefix" value="30"/>
<property name="suffix" value="A"/>
<property name="initial" value="1001000"/>
</bean>
Spring2.0后缩写形式
<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"
p:prefix="30" p:suffix="B" p:initial="101000" />
</beans>
Map属性配置
<property name="suffixes">
<map>
<entry>
<key>
<value>type</value>
</key>
<value>A</value>
</entry>
<entry>
<key>
<value>url</value>
</key>
<bean class="java.net.URL">
<constructor-arg value="http"/>
<constructor-arg value="www.cgydawn.com"/>
<constructor-arg value="/"/>
</bean>
</entry>
</map>
</property>
Map简化配置
<map>
<entry key="type" value="A"/>
<entry key="url">
<bean class="java.net.URL">
<constructor-arg value="http"/>
<constructor-arg value="www.cgydawn.com"/>
<constructor-arg value="/"/>
</bean>
</entry>
</map>
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
</beans>