1、spring的普通属性注入
参见:spring文档3.3章节
什么是属性编辑器,作用?
* 自定义属性编辑器,spring配置文件中的字符串转换成相应的对象进行注入
spring已经有内置的属性编辑器,我们可以根据需求自己定义属性编辑器
* 如何定义属性编辑器?
* 继承PropertyEditorSupport类,覆写setAsText()方法,参见:UtilDatePropertyEditor.java
* 将属性编辑器注册到spring中,参见:applicationContext-editor.xml
依赖对象的注入方式,可以采用:
* ref属性
* <ref>标签
* 内部<bean>来定义
如何将公共的注入定义描述出来?
* 通过<bean>标签定义公共的属性,指定abstract=true
* 具有相同属性的类在<bean>标签中指定其parent属性
参见:applicationContext-other.xml
<bean id="bean1" class="com.spring.Bean1">
<property name="strValue" value="Hello"/>
<!--
<property name="intValue" value="123"/>
-->
<property name="intValue">
<value>123</value>
</property>
<property name="listValue">
<list>
<value>list1</value>
<value>list2</value>
</list>
</property>
<property name="setValue">
<set>
<value>set1</value>
<value>set2</value>
</set>
</property>
<property name="arrayValue">
<list>
<value>array1</value>
<value>array2</value>
</list>
</property>
<property name="mapValue">
<map>
<entry key="k1" value="v1"/>
<entry key="k2" value="v2"/>
</map>
</property>
<property name="dateValue">
<value>2008-08-15</value>
</property>
</bean>
<bean id="bean2" class="com.bjsxt.spring.Bean2">
<property name="bean3" ref="bean3"/>
<property name="bean4">
<ref bean="bean4"/>
</property>
<property name="bean5" ref="bean5"/>
</bean>
<!--
<bean id="bean3" class="com.bjsxt.spring.Bean3">
<property name="id" value="1000"/>
<property name="name">
<value>Jack</value>
</property>
<property name="password" value="123"/>
</bean>
<bean id="bean4" class="com.bjsxt.spring.Bean4">
<property name="id" value="1000"/>
<property name="name" value="Jack"/>
</bean>
-->
<bean id="bean5" class="com.bjsxt.spring.Bean5">
<property name="age" value="20"/>
</bean>
</beans>
属性编辑器:
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="com.bjsxt.spring.UtilDatePropertyEditor">
<property name="format" value="yyyy-MM-dd"/>
</bean>
</entry>
</map>
</property>
</bean>
<!--
<bean id="utilDatePropertyEditor" class="com.bjsxt.spring.UtilDatePropertyEditor"></bean>
-->
public class UtilDatePropertyEditor extends PropertyEditorSupport {
private String format="yyyy-MM-dd";
@Override
public void setAsText(String text) throws IllegalArgumentException {
System.out.println("UtilDatePropertyEditor.saveAsText() -- text=" + text);
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date d = sdf.parse(text);
this.setValue(d);
} catch (ParseException e) {
e.printStackTrace();
}
}
public void setFormat(String format) {
this.format = format;
}
}
<bean id="beanAbstract" abstract="true">
<property name="id" value="1000"/>
<property name="name" value="Jack"/>
</bean>
<bean id="bean3" class="com.bjsxt.spring.Bean3" parent="beanAbstract">
<property name="name" value="Tom"/>
<property name="password" value="123"/>
</bean>
<bean id="bean4" class="com.bjsxt.spring.Bean4" parent="beanAbstract"/>