先看一下官网给出的作用域
我们主要学习singletion(单例模式,Spring的默认作用域,只有一个对象),prototype(原型模式)每次创建都是一个性的对象
先创建一个实体类
package com.zkw.pojo;
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "user{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
配置文件,在这里注入我使用了c命名空间注入值和p命名空间注入值
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--bean的作用 singleton:单例模式 ; prototype:原型-->
<!--p命名空间注入值-->
<bean id="user" class="com.zkw.pojo.User" p:name="V" p:age="24" scope="singleton"/>
<!--c命名空间注入值-->
<bean id="userT" class="com.zkw.pojo.User" c:name="112" c:age="23" scope="prototype"/>
</beans>
测试代码
import com.zkw.pojo.Student;
import com.zkw.pojo.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
@Test
public void cpTest(){
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
User user = context.getBean("user", User.class);
User user2 = context.getBean("user", User.class);
System.out.println("singleton:user.equals(user2)="+(user.equals(user2)));
System.out.println(user.toString());
System.out.println("=====================");
User userT = context.getBean("userT", User.class);
User userT2 = context.getBean("userT", User.class);
System.out.println("prototype:userT.equals(userT2)="+(userT.equals(userT2)));
System.out.println(userT.toString());
}
}
结果如下