读书人

Spring属性流入和构造函数注入参考

发布时间: 2012-06-27 14:20:09 作者: rapoo

Spring属性注入和构造函数注入参考

个人学习参考所用,勿喷!

?

1.Pojo如下:

package com.beans;import java.util.Date;import java.util.List;import java.util.Map;import java.util.Set;import java.util.Properties;public class Firstbean {private int intValue;private String strValue;private List<?> listValue;private Set<?> setValue;private Map<?,?> mapValue;private String[] strValues;private Properties props;private Date dateValue;private Secondbean sb;public Firstbean() {}public Firstbean(int intValue, String strValue) {this.intValue = intValue;this.strValue = strValue;}//get set方法均省略}

?

2.applicationContext.xml中的属性注入方式如下(包括各种基本类型、集合类型、时间类型和自定义类型的注入):

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="firstbean" value="123" /><property name="strValue" value="123" /><!--各种常用集合类型的注入--><property name="listValue"><list><value>listValue1</value><value>listValue2</value></list></property><!--Spring默认集合中的元素作为字符串对待 --><property name="setValue"><set><value type="int">123</value><value type="int">listValue</value></set></property><property name="mapValue"><map><entry key="key1" value="value1" /><entry key="key2" value="value2" /></map></property><property name="strValues"><list><value>array1</value><value>array2</value></list></property><property name="props"><props><prop key="key1">value1</prop><prop key="key2">value2</prop></props>                </property><!--时间类型的注入--><property name="dateValue"><value>2011-2-22</value></property><!--自定义类型的注入,使用local属性则只检测本XML文件--><property name="sb" ref="secondbean" /></bean><!-- 尤其要注意这里的对时间类型注入方式的要求,已经内部Bean的声明  --><bean id="customEditorConfigurer" value="yyyy-MM-dd" /></bean></entry></map></property></bean><bean id="secondbean " /></beans>
?

3.构造函数方式的注入如下:

<bean id="firstbean1" type="int" value="123" /><constructor-arg index="1" type="java.lang.String" value="abc" /></bean>
?

?

?

?

读书人网 >软件架构设计

热点推荐