社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
1、创建Java项目:File -> New -> Java Project
2、引入必要jar包,项目结构如下
3、创建People实体类People.java
package com.spring.model;
public class People {
private int id;
private String name;
public People() {
super();
System.out.println("Create People");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "People [id=" + id + ", name=" + name + "]";
}
}
4、创建spring配置文件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="prototypePeople" class="com.spring.model.People" scope="prototype">
<property name="id" value="0"></property>
<property name="name" value="prototypePeople"></property>
</bean>
<!--单例模式,加载applicationContext.xml时初始化对象-->
<bean id="singletonPeople" class="com.spring.model.People" scope="singleton">
<property name="id" value="0"></property>
<property name="name" value="singletonPeople"></property>
</bean>
</beans>
5、创建Spring测试类SpringUnit.java
package com.spring.junit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringUnit {
ClassPathXmlApplicationContext ctx = null;
@Before
public void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void test() {
System.out.println(ctx.getBean("prototypePeople") == ctx.getBean("prototypePeople"));
System.out.println(ctx.getBean("singletonPeople") == ctx.getBean("singletonPeople"));
}
@After
public void tearDown() throws Exception {
ctx.close();
}
}
6、测试结果
... 省略Spring日志信息 ...
Create People
Create People
Create People
false
true
... 省略Spring日志信息 ...
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!