zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    SQL中UNION的使用
    [转]身份证号准确性检测
    shell中if/seq/for/while/until
    shell中数字、字符串、文件比较测试
    shell简介及变量的定义查看撤销
    grep/字符/次数匹配/锚定符/小大括号/wc/tr/cut/sort/uniq
    linux全局和个人配置文件说明
    linux文件的3个时间和7种文件类型
    linux常用配置文件和命令总结
    目录方式扩展swap分区大小
  • 原文地址:https://www.cnblogs.com/lastingjava/p/10005402.html
Copyright © 2011-2022 走看看