Scope:实体类
package com.student.scope;
public class Scope {
}
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">
<!-- services -->
<bean id="bean4" class="com.student.scope.Scope" scope="singleton">
</bean>
</beans>
scopeTest:测试类
package com.student.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.student.instance.constructor.Bean1;
public class ScopeTest {
public static void main(String[] args) {
String xmlPath = "com/student/scope/bean4.xml";
ApplicationContext applicationContext =new ClassPathXmlApplicationContext(xmlPath);
Scope scope1 =(Scope)applicationContext.getBean("bean4");
Scope scope2 =(Scope)applicationContext.getBean("bean4");
System.out.println(scope1);
System.out.println(scope2);
}
}
输出结果:
十月 13, 2019 5:04:32 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@46f7f36a: startup date [Sun Oct 13 17:04:32 CST 2019]; root of context hierarchy
十月 13, 2019 5:04:32 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/student/scope/bean4.xml]
com.student.scope.Scope@6a024a67
com.student.scope.Scope@6a024a67
修改成多例(原型):
<?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">
<!-- services -->
<bean id="bean4" class="com.student.scope.Scope" scope="prototype">
</bean>
</beans>
输出结果:
十月 13, 2019 5:10:21 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@46f7f36a: startup date [Sun Oct 13 17:10:21 CST 2019]; root of context hierarchy
十月 13, 2019 5:10:21 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/student/scope/bean4.xml]
com.student.scope.Scope@32e6e9c3
com.student.scope.Scope@5056dfcb
总结:1.如果不定义scope属性,系统默认是单例的,也就是同一个实体类,spring容器只能创建同一个实例。
2.prototype 原型 也叫多例,对于同一个实体类,每次生成的实例(scope1,scope2)都是不同的。
浙公网安备 33010602011771号