Spring单例和多例

使用bean的scope属性来控制单例和多例:

    <!-- bean 的 scope属性可以控制单例和多例
        singleton是默认值:单例的 ;
        prototype:   多例的;
        request:  在web应用中每次请求重新实例化;
        session:  在web应用中每次会话重新实例化;
     -->
    <bean id="people" class="com.spring.pojo.People" scope="singleton"></bean>
    <bean id="people2" class="com.spring.pojo.People" scope="prototype"></bean>

 

测试代码:

public class Test {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
//        String[] beans = applicationContext.getBeanDefinitionNames();
//        System.out.println(Arrays.toString(beans));
        People people1 = applicationContext.getBean("people",People.class);
        People people2 = applicationContext.getBean("people",People.class);
        System.out.println(people1==people2);
        
        People people3 = applicationContext.getBean("people2",People.class);
        People people4 = applicationContext.getBean("people2",People.class);
        System.out.println(people3==people4);
    }
}

控制台输出:

true
false

单例设计模式,懒汉式: 由于加了锁,所以效率低,于是产生了饿汉式

//单例设计模式:懒汉式
public class Teacher {
    private static Teacher teacher;
    private Teacher() {}
    public static Teacher getInstance() {
        if(teacher==null) {
            //考考虑到多线程,双重判断
            synchronized(Teacher.class) {
                if(teacher==null) {
                    teacher=new Teacher();
                }
            }
        }
        return teacher;
    }
}

单例设计模式,饿汉式:

//单例设计模式:饿汉式
public class Teacher {
    //在对象实例化里就赋值
    private static Teacher teacher = new Teacher();
    private Teacher() {}
    public static Teacher getInstance() {
        return teacher;
    }
}

 

转载于:https://www.cnblogs.com/lastingjava/p/10005402.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值