(一)scope=“singleton”
知识点:无论获取多少个bean,得到的总是一样的地址,singleton范围下只会创建一个bean实例
1.Bean4.java
package com.inspur.scope; public class Bean4 { }
2.InstanceTest.java
package com.inspur.scope; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.inspur.static_factory.Bean2; public class InstanceTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String xmlPath = "com/inspur/scope/beans4.xml"; //2.ApplicationContext 在加载文件时,对bean实例化 ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath); Bean4 bean4 = (Bean4) applicationContext.getBean("bean4"); System.out.println(bean4); Bean4 bean5 = (Bean4) applicationContext.getBean("bean4"); System.out.println(bean5); } }
3.bean4.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="bean4" class="com.inspur.scope.Bean4" scope="singleton"></bean> </beans>
4.此时的运行结果是:
5.如果将更改为prototype则获得两个不同的值。
运行结果如下: