分别使用singleton和prototype作用域创建Bean实例,比较singleton和prototype作用域的区别。
1. 创建项目
Idea创建Java项目,项目名称为:case06-spring-student05。
2. 导入spring相关jar包
case05-spring-student04项目下创建lib目录,在lib目录下导入Jar包:
-
核心包
spring-core-5.3.25.jar
spring-beans-5.3.25.jar
spring-context-5.3.25.jar
spring-expression-5.3.25.jar
-
测试包
junit-4.6.jar
-
依赖包
commons-logging-1.2.jar
3. 创建Spring配置文件
src目录下创建applicationContext.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="singletonBean" class="com.wfit.student.SingletonBean" scope="singleton"/>
<!--原型模式-->
<bean id="prototypeBean" class="com.wfit.student.PrototypeBean" scope="prototype"/>
</beans>
4. 创建SingletonBean类
src目录下创建com.wfit.student包,此包目录下创建SingletonBean类。
public class SingletonBean {
public SingletonBean(){
System.out.println("singleton...");
}
}
5. 创建PrototypeBean类
com.wfit.student目录下创建PrototypeBean类。
public class PrototypeBean {
public PrototypeBean(){
System.out.println("prototype...");
}
}
6. 创建测试类
src目录下创建com.wfit.test包,此包目录下创建TestStudent测试类。
public class TestStudent {
@Test
public void testSingleton(){
//初始化Spring容器ApplicationContext,加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
SingletonBean bean1 = applicationContext.getBean("singletonBean",SingletonBean.class);
SingletonBean bean2 = applicationContext.getBean("singletonBean",SingletonBean.class);
System.out.println(bean1 == bean2);
}
@Test
public void testPrototype(){
//初始化Spring容器ApplicationContext,加载配置文件
ApplicationContext applicationContext =
new ClassPathXmlApplicationContext("applicationContext.xml");
PrototypeBean bean1 = applicationContext.getBean("prototypeBean",PrototypeBean.class);
PrototypeBean bean2 = applicationContext.getBean("prototypeBean",PrototypeBean.class);
System.out.println(bean1 == bean2);
}
}
7. 执行结果
-
testSingleton执行结果
testPrototype执行结果