Spring framework bean的作用域,生命周期

Spring beand的作用域

设置为singleton时,相当于一个类只能有一个实例,当再次申请时,返回的是同一个实例

可以看到两个bean实例的hashcode值是一样的,说明在此申请到的是同一个实例
将bean的作用域设置为prototype时,再次运行,可以看到,申请到的是两个不同bean实例

目前只学习了prototype作用域和singleton作用域,剩下的等待之后学习

Spring bean的生命周期
1、定义 配置xml文件的过程
2、初始化 ioc容器对bean、进行实例化
3、使用
4、销毁 ioc容器停止时销毁所有由bean容器创建的bean实例

初始化和销毁都有三种方式
1,实现接口,InitializingBean,DisposableBean
2,在每个bean中定义init-method和destroy-method
3,在xml配置文件中定义默认的default-init和default-destroy方法

/*
 * public void defautinit() { System.out.println("Bean defaut Init." +
 * this.hashCode()); }
 * 
 * public void defautdestroy() { System.out.println("Bean defaut destroy." +
 * this.hashCode()); }
 */


/*
 * @Override public void destroy() throws Exception {
 * System.out.println("Bean destory."+this.hashCode()); }
 * 
 * @Override public void afterPropertiesSet() throws Exception {
 * System.out.println("Bean init."+this.hashCode()); }
 */

/*
 * public void start() { System.out.println("Bean start."+this.hashCode()); }
 * 
 * public void stop() { System.out.println("Bean stop."+this.hashCode()); }
 */

接口定义的初始化和销毁方法优先级大于bean中定义的方法,
xml默认的方法优先级最低,甚至可以不在bean中实现,也不会报错,如果实现另外两种,会被覆盖
如果在bean中设置了init和destroy方法则一定需要实现,否则会启动失败

慕课网https://www.imooc.com/video/3751

猜你喜欢

转载自www.cnblogs.com/wjune-0405/p/12148683.html