xml注入属性的方式
set 方法注入
<bean id="userService" class="com.qj.ioc.UserServiceImpl">
<property name="name" value="小明"/>
</bean>
有参构造函数注入
<bean id="student" class="com.qj.ioc.Student">
<constructor-arg name="name" value="小明"/>
</bean>
p 名称空间注入(不常用)
添加名称空间
xmlns:p=”http://www.springframework.org/schema/p“
在 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userService" class="com.qj.ioc.UserServiceImpl" p:name="小明"/>
</beans>
在属性中设置空值
<bean id="userService" class="com.qj.ioc.UserServiceImpl">
<property name="name">
<null/>
</property>
</bean>
防止特殊字符:<![CDATA[]]>
<bean id="userService" class="com.qj.ioc.UserServiceImpl">
<property name="name">
<value><![CDATA[<>""$%^]]></value>
</property>
</bean>
注入外部 bean-ref
<bean id="userService" class="com.qj.ioc.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="userDao" class="com.qj.ioc.UserDaoImpl"/>
注入内部 bean-嵌套
内部 bean 的 id 是多余的
<bean id="staff" class="com.qj.ioc.Staff">
<property name="name" value="小明"/>
<property name="dept">
<bean class="com.qj.ioc.Dept">
<property name="name" value="研发部门"/>
</bean>
</property>
</bean>
级联赋值
可以使用 . 赋值对象属性的属性
前提是 dept 有 get 方法
<bean id="staff" class="com.qj.ioc.Staff">
<property name="name" value="小明"/>
<property name="dept.name" value="研发部门"/>
</bean>
注入集合属性
<bean id="setStaff" class="com.qj.ioc.Staff">
<property name="array">
<array>
<value>初级</value>
<value>中级</value>
<value>高级</value>
</array>
</property>
<property name="list">
<list>
<value>初级</value>
<value>中级</value>
<value>高级</value>
</list>
</property>
<property name="map">
<map>
<entry key="姓名" value="小明"/>
<entry key="年龄" value="28"/>
</map>
</property>
<property name="set">
<set>
<value>Java</value>
<value>Python</value>
</set>
</property>
</bean>
在集合里设置对象类型的值:
使用 ref
<list>
<ref bean="beanId"/>
</list>
抽取注入的集合:
1.名称空间引入 util
<?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:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
</beans>
2.使用 util 标签
<util:list id="bookList">
<value>数学课本</value>
<value>语文课本</value>
</util:list>
3.使用 ref 使用抽取的集合
<property name="list" ref="bookList"/>
FactoryBean(工厂 Bean)
相对于普通 Bean,FactoryBean 配置文件中定义的类型与返回的类型可以不一致
实现一个工厂 Bean:
1.创建类,实现接口 FactoryBean
2.在实现方法中定义返回的 bean 类型
设置 Bean 为多实例/单例(默认)
scope 属性可以设置 bean 是单例对象还是多实例对象
<bean id="user" class="com.qj.ioc.User" scope="singleton"/>
singleton: 单例
prototype: 多示例