spring

    科技2026-01-11  16

    单例与多例

    单例是什么? 内存中只有一个对象,每次获取到该对象的地址值一样. 》多实例是什么? 内存中的每个对象都是一个新的对象,他们的地址值都不同.

    (1)问题: 每次获取对象的时候,spring是新创建一个对象还是始终给我们返回同一个对象. (2)答案: spring默认的情况下创建的对象都是单例的. (每次返回的对象都是同一个)

    scope="singleton" 单例(默认值) scope="prototype" 多例 scope="request" 创建的对象放到request域中 scope="session" 创建对象放到session对象

    单实例

    <bean id="person" class="com.wzx.domain.Person" scope="prototype"/>

    多实例

    <bean id="person" class="com.wzx.domain.Person" scope="singleton"/>

    单例设计模式的实现

    public class Singleton { private static Singleton instance; // 私有构造器 private Singleton (){} //使用静态变量修饰方法,以便直接调用 // 使用synchronized修饰确保线程安全,每次调用只返回一个对象 public static synchronized Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }

    测试代码

    public class PersonTest { @Test public void Test01(){ Singleton instance1 = Singleton.getInstance(); Singleton instance2 = Singleton.getInstance(); System.out.println(instance1); System.out.println(instance2); }

    测试结果

    Processed: 0.016, SQL: 9