1、spring配置文件的根元素是来源spring bean命名空间所定义的<beans>元素:
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"></beans>
2、构造器注入
<bean id="fighter" class="com.cn.bean.Fighter"> <constructor-arg value="15" /> <constructor-arg ref="figterBlock" /> </bean>
3、单例类创建:
package spring.study.spring.bean; public class FighterSingle { private FighterSingle(){ System.out.println("create FighterSingleHolder"); } private static class FighterSingleHolder{ static FighterSingle instance = new FighterSingle(); } public static FighterSingle getInstance(){ return FighterSingleHolder.instance; } public void say(){ System.out.println("I'm a FighterSingleHolder"); } }
在spring上下文配置:
<bean id="fighterSingle" class="spring.study.spring.bean.FighterSingle" factory-method="getInstance"/>
但是即使不声明后面的factory-method也是可以正常创建的,这是为什么?
4、Bean的作用域:
<bean id="fighterBlock" class="spring.study.spring.bean.FighterBlock" scope="prototype"/>
singleton:在每一个spring容器中,一个Bean定义只有一个对象实例(默认)
prototype:允许Bean的定义可以被实例化任意次(每次调用都创建一个实例)
request:在一次HTTP请求中,每个Bean定义对应一个实例,该作用域仅在基于web的spring上下文中才有效
session:在一个HTTP session中,每个Bean定义对应一个实例。该作用域仅在基于web的spring上下文中才有效
global-session:在一个全局HTTP session中,每个Bean定义对应一个实例。该作用域仅在Porlet上下文中才有效
5、初始化和销毁Bean
<bean id="fighterBlock" class="spring.study.spring.bean.FighterBlock" init-method="init" destroy-method="destroy"/>
或者可以在<beans .... default-init-method="init" default-destroy-method="destroy" >
或者让Bean实现spring的InitializingBean和DisposableBean接口
6、注入Bean属性:
<bean id="student" class="spring.study.spring.bean.Student" > <property name="name" value="kangkang" /> <property name="monitor" ref="monitor" /> </bean> <bean id="monitor" class="spring.study.spring.bean.Monitor"> <property name="name" value="Mrs wang" /> <property name="age" value="35" /> </bean>
内部Bean:
<bean id="student2" class="spring.study.spring.bean.Student" > <property name="name" value="kangkang" /> <property name="monitor"> <bean class="spring.study.spring.bean.Monitor" /> </property> </bean>