Spring bean 的配置
一. bean的配置项 id class<不可缺少的> scope constructor arguments peroperties autowiring mode lazy-initialization mode initialization/destruction mode 二.bean的作用域 singleton:单列,在bean容器中只存在一份 prototype:每次请求都会产生新的实例,destroy方式不生效
public void testSay() { BeanScope beanScope = super.getBean("beanScope"); beanScope.say(); BeanScope beanScope2 = super.getBean("beanScope"); beanScope2.say(); }//当scope=singleton时 beanscope与beanscope2是同一个实例,拥有相同的hashcode,当 scope=prototype 是两个不同的实例 连接bean容器: ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("springxmlpath"); 在@Before中context.start() 在@after中context.destroy()request session global session
Bean的生命周期 一.生命周期:定义-初始化-使用-销毁 二.初始化: 1.配置init-method:
public class examplebean{ public void init(){ //do some initialization work } }2.实现InitializingBean接口,覆盖afterPropertiesSet()throws Exception;(与上面类似):
public class exapleInitializingBean implements InitializingBean{ @override public void afterPropertiesSet(){ //do some initialization work } }三.bean的销毁(同上) 1.实现DisposableBean接口,覆盖destroy()方法 2.配置destroy-method 四.配置默认初始化和销毁方法:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd" default-init-method="init" default-destroy-method="destroy"> </beans>五.三种方法的执行顺序:实现InitializingBean/DisposableBean的执行方法最快,全局默认配置(是可选,即使配置了也可以不声明)会被 单元配置覆盖掉(配置了就必须要声明)
