构造器注入
Set方式注入
依赖:Bean对象的创建依赖于容器
注入:Bean对象中的所有属性由容器注入
基础数据类型注入:
直接value赋值即可
<property name="name" value="yi"/>
实体类数据bean注入:
用ref指向已生成的bean
<bean id="student" class="com.lms.pojo.Student">
<property name="address" ref="address"/>
</bean>
<bean id="address" class="com.lms.pojo.Address">
</bean>
数组、列表注入:
用array、list标签搭配value实现赋值:
<property name="book">
<array>
<value>1</value>
<value>2</value>
<value>3</value>
</array>
</property>
<property name="hobbys">
<list>
<value>1</value>
<value>2</value>
<value>3</value>
</list>
</property>
Map数据注入:
在Map插入一个个entry,且由key和value组成
<property name="card">
<map>
<entry key="yi" value="1"/>
<entry key="er" value="2"/>
</map>
</property>
Set数据注入:
直接value赋值即可
<property name="games">
<set>
<value>lol</value>
<value>cs</value>
</set>
</property>
null值:
设置null值
<property name="non">
<null/>
</property>
Properties数据注入:
properties也是类似map的键值对,由prop组成,也对应K-V键值对,只是value放的位置和map不同
<property name="info">
<props>
<prop key="id">123</prop>
<prop key="date">123</prop>
</props>
</property>
其他
P命名空间:
添加xmlns:p,后续可以直接用p:成员名进行赋值
<?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="user" class="com.lms.pojo.User" p:name="yi" p:age="12">
</bean>
</beans>
实际是调用Set方法注入方式进行注入
C命名空间:
导入xmlns:c,后续用c:成员名赋值
<?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:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user" class="com.lms.pojo.User" c:name="yi" c:age="18">
</bean>
</beans>
该方法实际是调用有参构造器进行赋值
Bean作用域
单例模式
为Spring默认机制
<bean id="user" class="com.lms.pojo.User" scope="singleton">
原型模式
每次取都创造一个新的,多例模式
<bean id="user" class="com.lms.pojo.User" scope="prototype">
其余request、session、application
只在web环境使用,如只在请求中存活、只在session存活、全局存活等