2019-04-08

bean(实体或对象)配置项和作用域和生命周期

1.配置项
id:(唯一)
class:(必须)
scope:作用域
constructor arguments:构造器参数
properties:设值属性
autowiring mode:自动装配模式
lazy-initializatin mode:懒加载模式
initialization/destructin method:初始化/销毁方法
2.作用域
singleton(default):单例,一个bean容器中只一份(比如两对象加载同一实例,每个对象中都是一份那个实例)


public void test(){  //同一个bean容器中
  Bean bean1=super.getBean("bean");
  bean.say(); //输出该实例的this.hashCode();(每实例唯一)
  Bean bean2=super.getBean("bean");
  bean2.say();//两个对象方法输出相同
}

prototype:每次(ioc)请求创建新实例,destory不生效(因为每次请求后该实例不再使用,直接被回收)


//代码同上,输出不同

request:每次http请求创建一个实例,仅在当前request有效
session:同上
global session:基于portlet的web中有效(portlet定义global session),web中同session
3.生命周期
初始化(销毁):(1)实现org.springframework.beans.factory.InitializingBean(.DisposableBean)接口,覆盖afterPropertiesSet(destroy)方法(2)配置init-method(destroy-method)

public class XInitializingBean implements  InitializingBean{
  @Override
  public void afterPropertiesSet() throws Exception{  //do some work
  }
}

//destroy-method="cleanup"
public class XBean{
  public void init(){//init work(cleanup)
  }
}

(3)全局默认初始化,销毁方法




(注:test方法在UnitTestBase中@Before@After)
当以上三种方法都有时,先执行全局默认方法,然后再执行自己设置的

你可能感兴趣的:(2019-04-08)