Spring in action 学习(2)创建Bean

来源:互联网 发布:产品外观结构设计软件 编辑:程序博客网 时间:2024/05/22 06:26

2种方式

-BeanFactory    XMLBeanFactory(newFileSystemResource..)-ApplicationContext    ClassPathXmlApplicatioContext("foo.xml");    FileSystemXmlApplicationContext("c:/foo.xml");

注入属性

通过构造函数-<constructor-arg value="15">-<constructor-arg ref="xxx">set注入-<property name="song" value="15">-<property name="song" ref="xxx">

spring 装配支持的集合类型

- <list>- <set>- <map>- <props> 键值对,不过都是string类型对应于配置文件中,以instruments为例<property name="instruments">    <list>        <ref bean="guitar"/>        <ref bean="cymbal"/>        <ref bean="harmonica"/>    </list></property>set类似<map>    <entry key="GUITAR" value-ref="guitar"/>    <entry....></map>entry:  key key-ref,  value value-ref.<prop key="GUITAR">STRUM STRUM STRUM</prop>设置属性值为空:<property name="someNonNullProperty"><null/></property>

自动装配

byName

<bean id="kenny" class="xxx">    <property name="instrument" ref="saxophone"/></bean><ben id="instrument" class="xxx">则上面可变为:<bean id="kenny" class="xxx" autoware="byName">

byType

constructor

autodetect

默认自动装配

<beans default-autowire="byName">    ...

控制Bean创建

每次都创建一个新的bean

<bean id=".." calss="..."    scope="prototype"/>

scope

singleton  :一个实例prototype  :多个实例request    :http请求session    :http会话global-session :全局http会话

单例类

factory-method="getInstance" />

初始化和销毁

<bean id="xxx" class="xxx"    init-method="init"    destroy-method="clean">

高级Bean装配

abstract="true"  为抽象类<bean id="xxx" parent="xxx.class"> 声明该bean的父类是什么可以覆盖相应属性值。
0 0
原创粉丝点击