java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Bean作用域 生命周期

一文搞懂Spring Bean中的作用域和生命周期

作者:倔强的牛角

Spring作为当前Java最流行、最强大的轻量级框架,受到了程序员的热烈欢迎。了解Spring Bean的作用域与生命周期是非常必要的,快跟随小编一起学习学习吧

一、Spring Bean 作用域

常规的 Spring IoC 容器中Bean的作用域有两种:singleton(单例)和prototype(非单例)

注:基于Web的容器还有其他种作用域,在这就不赘述了。

singleton(单例)

案例1

1.创建Dept类

public class Dept {
    //部门编号
    private int deptNo;
    //部门名称
    private String deptName;
}

2.编写Spring配置文件,并将scope 属性设置为singleton

<bean id="dept" class="com.bighorn.pojo.Dept" scope="singleton">
</bean>

3.编写运行程序

public static void main(String[] args) {
    //获取IoC容器
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    //从容器中获取对象
    Dept dept1 = context.getBean("dept", Dept.class);
    Dept dept2 = context.getBean("dept", Dept.class);
    //打印对象
    System.out.println(dept1);
    System.out.println(dept2);
}

4.结果如下,可以发现打印出的是同一个对象

prototype(原型)

案例2

1.只需修改scope 属性为prototype,其他代码不变。

<bean id="dept" class="com.bighorn.pojo.Dept" scope="prototype">
</bean>

2.运行结果如下

小结

spring bean默认为单例,避免了对象的频繁创建与销毁,达到了bean对象的复用,性能高。

像表现层、业务层、数据层、工具类对象只需要调用方法,比较适合交给Spring IoC容器管理

但是像那种需要封装实例的域对象,因为会引发线程安全问题,不适合交给Spring IoC容器管理。

二、Spring Bean生命周期

Spring Bean生命周期:Spring Bean 对象从创建到销毁的整体过程。

Spring Bean生命周期大致可以分为以下 5 个阶段:1.Bean 的实例化、2.Bean 属性赋值、3.Bean 的初始化、4.Bean 的使用、5.Bean 的销毁

Spring 根据 Bean 的作用域来选择 Bean 的管理方式。

综上所述: 为了更好研究如何控制bean周期,下面案例中创建的bean默认都使用单例模式。

如何关闭容器

由于ApplicationContext类中没有关闭容器的方法,所以想要关闭容器需要用到ApplicationContext的子类——ClassPathXmlApplicationContext类。该类又有两种方法可以关闭容器

1、close关闭容器

close()方法,在调用的时候关闭容器

//获取 ClassPathXmlApplicationContext 容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//调用close方法关闭容器
context.close();

2、注册钩子关闭容器

registerShutdownHook()方法,在JVM退出前调用关闭容器

//获取 ClassPathXmlApplicationContext 容器
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//调用注册狗子关闭容器
context.registerShutdownHook();

生命周期回调

Bean 的生命周期回调方法主要有两种:

我们可以通过以下 2种方式自定义 Bean 的生命周期回调方法:

通过接口设置生命周期

我们可以在 Spring Bean 的 Java 类中,通过实现 InitializingBeanDisposableBean 接口,指定 Bean 的生命周期回调方法。

案例1

1.创建User类,并实现InitializingBean, DisposableBean接口,重写afterPropertiesSet()destroy()方法。代码如下

/**
 * 继承接口,程序初始化回调和销毁回调方法
 */
public class User implements InitializingBean, DisposableBean {
    String name;
    int age;

    //setter方法
    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    //初始化回调方法
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("这是初始化回调方法");
    }

    //销毁回调方法
    @Override
    public void destroy() throws Exception {
        System.out.println("这是销毁回调方法");
    }

    //toString方法
    @Override
    public String toString() {
        return "User{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }
}

2.编写spring配置文件

<bean id="user" class="com.bighorn.pojo.User">
    <property name="name" value="bighorn"/>
    <property name="age" value="18"/>
</bean>

3.编写运行程序

public class App {
    public static void main(String[] args) {
        //获取 ClassPathXmlApplicationContext 容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //从容器中获取对象
        User user = context.getBean("user", User.class);
        //使用bean
        System.out.println(user);
        //调用close方法关闭容器
        context.close();
    }
}

4.运行结果如下

通过xml设置生命周期

注意:由于通过接口设置生命周期的方式会导致代码的耦合性过高,所以通常情况下,我们会通过xml设置生命周期。

通过 <bean> 元素中的 init-methoddestory-method 属性,指定 Bean 的生命周期回调方法。

案例2

1.创建User类,这次不需要继承那两个接口了,但要在添加两个普通方法(方法名可任意):init()destory()代表初始化和销毁方法。代码如下

/**
 * 通过XML配置指定回调方法
 */
public class User {
    String name;
    int age;

    //setter方法
    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    //初始化回调方法
    public void init() throws Exception {
        System.out.println("这是初始化回调方法");
    }

    //销毁回调方法
    public void destroy() throws Exception {
        System.out.println("这是销毁回调方法");
    }

    //toString方法
    @Override
    public String toString() {
        return "User{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }
}

2.编写spring配置文件,在<bean>元素里添加init-methoddestroy-method属性,并指定User类中自定义的init和destory方法(关键)

<!--通过XML配置指定回调方法-->
<bean id="user" class="com.bighorn.pojo.User" init-method="init" destroy-method="destroy">
    <property name="name" value="bighorn"/>
    <property name="age" value="18"/>
</bean>

3.运行程序和运行结果都与案例1相同,这里就少些笔墨介绍了

到此这篇关于一文搞懂Spring Bean中的作用域和生命周期的文章就介绍到这了,更多相关Spring Bean作用域 生命周期内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文