Spring的Bean管理(XML方式)
1.bean标签的常用属性
id:bean的名字,可以使用字母、数字、下划线、句号、冒号,不能有其他的特殊符号
name:和id相似,可以出现特殊字符。没有id,name也可以当成id使用
scope:
singleton:单例方式,默认值可以不设置
prototype:多例
request:WEB项目中,Spring创建一个对象,并将对象存到request域中
session:WEB项目中,Spring创建一个对象,并将对象存到session域中
2.bean实例化的方式(如何创建对象)
使用类的无参构造方法创建(需要掌握)
使用静态工厂创建
使用实例工厂创建
3.DI(如何设置属性)
bean属性的注入(设置属性)
创建一个测试类Person类
设置两个属性:
private String name;
private int age;
生成get、set、toString方法,以及有参无参的构造方法
注入:如代码
<!--
通过有参数的构造方法设置属性
constructor-arg
name: 属性的名字
vlaue:要设置的值
-->
<bean id="person" class="pojo.Person">
<constructor-arg name="name" value="Tom"></constructor-arg>
<constructor-arg name="age" value = "20"></constructor-arg>
</bean>
<!--
通过set方法设置属性
前提:要设置的属性要有对应的set方法
-->
<bean id="person" class="pojo.Person">
<property name="name" value="John"></property>
<property name="age" value="20"></property>
</bean>
<!--
对象类型的注入
给对象类型的属性设置值
前提:类的某个属性的对象
ref:引入另一个Bean的id或name
-->
<bean id="car" class="pojo.Car">
<property name="name" value="BYD"></property>
<property name="owner" ref="person"></property>
</bean>
<!--
p名称空间注入
-->
<bean id="person" class="pojo.Person" p:name="Peter" p:age="20"></bean>
<bean id="car" class="pojo.Car" p:name="BYD" p:owner-ref="person"></bean>
<!--
复杂类型注入
-->
<bean id="person" class="pojo.Person">
数组的注入:
<property name="hobby">
<array>
<value>学习</value>
<value>学习1</value>
<value>学习2</value>
<value>学习3</value>
</array>
</property>
<property name="hobby1">
集合的注入:
<list>
<value>学习</value>
<value>学习1</value>
<value>学习2</value>
<value>学习3</value>
</list>
</property>
<property name="name" value="John"></property>
<property name="age" value="20"></property>
</bean>
4.IOC和DI的区别:
IOC:控制反转,把对象的创建交给Spring配置
DI:依赖注入,向类里面的属性中设置值
关系:依赖注入不能单独存在,需要在IOC基础之上完成操作
(个人理解:需要把类配置完成后才能对类中的属性进行设置)