spring学习之bean的生存范围和生命周期

1.bean的生存范围:

(1)Singleton:默认,单例

(2)Prototype:原型,非单例

(3)Request:在一次http请求中,容器会返回该bean的同一个实例,对于不同的请求,返回不同的实例。

(4)Session:请求的作用域变为session

(5)Gloabsession:全局session

request,session主要用于web之中

我们这次主要探讨singleton和prototype这2个生存范围

singleton是单例的;prototype是原型的,,每次都会创建一个实例。

如果scope为singleton,二者相等,如果scope为prototype,二者不相等。

实例代码

public class User {}配置文件<?xml version="1.0" encoding="UTF-8"?><beansxmlns=""xmlns:xsi=""xmlns:p=""xsi:schemaLocation=" "><bean name="user" class="com.qzp.model.User" scope="prototype"></bean></beans>测试代码public class TestScope {public static void main(String[] args) {ApplicationContext cxt=new ClassPathXmlApplicationContext("applicationContext.xml");User u1=(User)cxt.getBean("user");User u2=(User)cxt.getBean("user");System.out.println(u1.hashCode());System.out.println(u2.hashCode());<span style="color:#FF0000;">//如果scope为singleton,二者相等,如果scope为prototype,二者不相等。</span>System.out.println(u1==u2);}}2.bean的生命周期

(1)lazy-init:懒加载,如果为true,该bean会延时加载,如果为false,该bean会立刻加载,默认为true

(2)init-method:初始化方法

<bean name="user" class="com.qzp.model.User" lazy-init="true" init-method="init" destroy-method="destroy" depends-on="student"></bean>其中init-method="init" init为类user中的init方法

(3)destory-method:销毁方法

(4)depends-on:某个bean的初始化依赖于另外一个bean的初始化

实例代码:

public class User {private String userName;private String password;public User() {super(); System.out.println("User的构造方法….");}public void init() {         System.out.println("User的初始化方法…");     }     public void destroy() {         System.out.println("User的销毁方法…");     }public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}public class Student {private String name;private int age;public Student() {super();System.out.println("student的构造方法…");}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}}

配置文件

<?xml version="1.0" encoding="UTF-8"?><beans    xmlns=""    xmlns:xsi=""    xmlns:p=""    xsi:schemaLocation="     ">    <bean name="user" class="com.qzp.model.User" lazy-init="true" init-method="init" destroy-method="destroy" depends-on="student"></bean>    <bean name="student" class="com.qzp.model.Student"></bean></beans>测试代码:public class TestLifeCycle{public static void main(String[] args) { AbstractApplicationContext cxt=new ClassPathXmlApplicationContext("applicationContext.xml");<span style="color:#FF0000;">//如果为懒加载,执行下面的代码时,才会执行到该类的构造方法。</span> cxt.getBean("user");cxt.close();}}测试结果如下:

student的构造方法…User的构造方法….User的初始化方法…User的销毁方法…

当一个人把寂寞当作人生预约的美丽,

spring学习之bean的生存范围和生命周期

相关文章:

你感兴趣的文章:

标签云: