一、BeanFactory与ApplicationContext的区别
(一)、BeanFactory
BeanFactory为spring的最原始接口,此接口的仅实现功能。
BeanFactory接口最大的特点就是在每次获取对象时才会创建对象
(二)、ApplicationContext
ApplicationContext为BeanFactory的孙子接口,功能更加丰富
ApplicationContext是每次容器启动时就会创建容器中配置的所有对象
其实现类有ClassPathXmlApplicationContext,FileSystemXmlApplicationContext
1.ClassPathXmlApplicationContext :从类路径下加载配置文件
2.FileSystemXmlApplicationContext :从硬盘绝对路径下加载配置文件
二、配置Bean中属性的方法:
1.属性注入:
<bean name="helloworld" class="com.milan.spring.HelloWorld">
<property name="username" value="kaka"></property>
<property name="helloworld" ref="其他bean的name名"></property>
</bean>
注意:property标签中,
name表示类中的属性,
value表示属性值,
ref表示引用的对象
2.构造器注入:
<bean name="helloworld" class="com.milan.spring.HelloWorld">
<constructor-arg name="username" value="milan"></constructor-arg>
<constructor-arg name="car" ref="其他bean的name名"></constructor-arg>
</bean>
注意:constructor-arg标签中,
name表示类中属性,
value表示属性值,
ref表示引用的对象,
index表示属性对应构造函数中参数的位置,
type表示对应的属性类型
3.p命名空间注入:走set方法
1.导入P名称空间 xmlns:p="http://www.springframework.org/schema/p"
2.使用p:属性完成注入
例如:
<bean name="user" class="cn.itcast.bean.User" p:name="kaka" p:age="22" p:car-ref="car" >
</bean>
4.spel注入
使用#{}表示属性值
5.特殊类型注入
<bean name="special" class="com.milan.spring.bean.Special">
<property name="array">
<array>
<value>value1</value>
<value>value2</value>
<ref bean="otherBeanName"/>
</array>
</property>
<property name="list">
<list>
<value>value1</value>
<value>value2</value>
<ref bean="otherBeanName"/>
</list>
</property>
<property name="map">
<map>
<entry key="key1" value="value1"></entry>
<entry key="key2" value="value2"></entry>
<entry key="key3" value-ref="beanName"></entry>
</map>
</property>
<property name="property">
<props>
<prop key="key1" >value1</prop>
</props>
</property>
</bean>
1.prototype:原型的,容器创建时不创建实例;每次获取bean,都创建一个新的bean
2.singleton:默认设置。单例的,容器创建时就创建默认实例。
3.session:4.request:
四、生命周期属性:
1.初始化:配置一个方法作为生命周期初始化方法spring会在对象创建之后立即调用
例如:init-method="初始化方法名"
2.销毁:spring容器在关闭并销毁容器中对象之前调用
例如:destroy-method="销毁方法名"
五、模块化配置:
<import resource="com/milan/spring/applicationContext.xml" />