目录
对象生成的发展历史:
- new Student();
- 简单工厂生成对象
- 使用Spring IOC
控制反转:
从需要自己new对象到直接从IOC容器中取对象为了更清晰的理解,IOC(控制反转)后改名为DI(依赖注入)
依赖注入 :
将属性值注入给属性,将属性注入给对象,将对象注入给IOC容器
注入方式:
- 使用property注入:底层实际上是运用到反射原理,调用pojo对象的set方法实现注入
- 使用constructor-arg注入:底层调用pojo对象的构造方法注入,注意顺序要与构造方法中的顺序一致
配置文件 applicationContext.xml
这个配置产生的所有对象,被Spring放到了一个称之为Spring IOC容器的一个地方
id:唯一标识符
class:指定实体类(实体类须提供get和set方法,无参构造等)
property:该类的属性
name:属性名
value:属性值
注意:当name为基本数据类型时,用value赋值
当name为对象类型时,用ref赋值,ref="需要指明对象Bean的id"
自动装配.如果bean对应的实体类中包含引用数据类型,那么当bean声明了autowire="byName"时,不需要再写这个引用类型的property,会在当前配置文件中寻找id为这个bean中的这个引用数据类型的名的对象,进行自动装配
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org /schema/context/spring-context-4.2.xsd
"
default-autowire="byName"
>
<!--上面default-autowire="byName" 为全局Bean设置自动装配-->
<!--添加扫描包-->
<context:component-scan base-package="dao">
</context:component-scan>
<bean id="student" class="pojo.Student">
<property name="stuNum" value="1"/>
<property name="name" value="moti"/>
<property name="age" value="20"/>
</bean>
<!--
使用p命名空间注入
简单类型-> p:属性名
引用类型-> p:属性名-ref
-->
<bean id="teacher1" class="pojo.Teacher" p:name="薛伟" p:age="20">
<!--
使用property注入
<property name="name" value="莫提"/>
<property name="age" value="30"/>
-->
<!--
使用constructor-arg注入
<constructor-arg value="莫提"/>
<constructor-arg value="30"/>
-->
</bean>
<bean id="course1" class="pojo.Course">
<!--推荐这种方式-->
<property name="name">
<value><![CDATA[<>@#$!%*&]]></value>
</property>
<property name="hours" value="45">
<!--赋值null时直接写,不再需要写value标签
<null/>
-->
<!--
赋值空字符串的时候,在value标签中什么都不要写
<value></value>
-->
</property>
<!--将teacher对象注入给course对象-->
<property name="teacher" ref="teacher1"/>
</bean>
<bean id="collections" class="pojo.Collections">
<property name="list">
<list>
<value>list1</value>
<value>list2</value>
<value>list3</value>
</list>
</property>
<property name="array">
<array>
<value>array1</value>
<value>array2</value>
<value>array3</value>
</array>
</property>
<property name="set">
<set>
<value>set1</value>
<value>set2</value>
<value>set3</value>
</set>
</property>
<property name="map">
<map>
<entry>
<key>
<value>key1</value>
</key>
<value>value-1</value>
</entry>
<entry>
<key>
<value>key2</value>
</key>
<value>value-2</value>
</entry>
<entry>
<key>
<value>key3</value>
</key>
<value>value-3</value>
</entry>
</map>
</property>
<property name="properties">
<props>
<prop key="props1">props1</prop>
<prop key="props2">props2</prop>
<prop key="props3">props3</prop>
</props>
</property>
</bean>
</beans>
留言