Spring中的DI(依赖注入)--给对象的属性赋值

来源:互联网 发布:2016中国软件城市排名 编辑:程序博客网 时间:2024/04/27 17:56

DI(依赖注入):给对象的属性赋值1,使用属性的setter方法进行注入:通过调用无参构造器或无参static工厂方法实例化bean之后,调用该bean的setter方法,即可实现基于setter的DI<!-- property是用来描述一个类的属性:直接变量(基本类型、String类型等)用value赋值,引用类型用ref赋值 --> <bean id="student" class="com.jxn.domain.Student" /><bean id="person" class="com.jxn.domain.Person"><!-- 直接变量 --><property name="name" value="aaa" /><!-- 引用类型 --><property name="student" ref="student"><!-- List --><property name="lists"><list><value>list1</value><ref bean="student"/><value>list3</value></list></property><!-- Map --><property name="map"><map><entry key="m1"><value>map1</value></entry><entry key="m2"><ref bean="student"/></entry></map></property><!-- Properties --><property name="properties"><props><prop key="key1">value1</prop><prop key="key2">value2</prop></props></property></bean>2,使用构造器注入:通过调用带参数的构造器来实现1)如果spring的配置文件的bean中没有<constructor-arg>标签,则调用默认的构造方法2)如果spring的配置文件的bean中有<constructor-arg>标签,则该元素确定唯一的构造方法,该标签的属性index  指参数的位置,从0开始type   指参数的类型,如果不写仍可确定唯一的构造方法,则可以省略type属性value  给基本类型赋值ref    给引用类型赋值<bean id="person" class="com.jxn.domain.Person"><constructor-arg index="0" type="java.lang.Long" value="1"></constructor-arg><constructor-arg index="1" value="zhangsan"></constructor-arg><constructor-arg index="2" ref="student"></constructor-arg></bean><bean id="student" class="com.jxn.domain.Student" />补充:    IoC        原理:把对象的创建、初始化、销毁等工作交给spring容器来做。由spring容器控制对象的生命周期。


0 0
原创粉丝点击