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; } }