Spring域标签scope的标签值如下
scope=“singleton”:(单例模型)
默认值,IoC容器中只存在一个Java类对象,此时Java对象为单例,即每次从IoC容器获取的Java对象都是同一个;
创建一个Student类,可不额外写其他代码
创建application.xml文件,且在application.xml文件中配置如下信息
<bean name="student" class="com.zzu.vo.Student" lazy-init="false" scope="singleton"></bean>
Test类中代码如下:
package spring;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zzu.vo.Student;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("application.xml");
Student student=(Student) applicationContext.getBean("student");
System.out.println(student);
student=(Student) applicationContext.getBean("student");
System.out.println(student);
}
}
得到如下结果:为同一个对象。
scope=“prototype”:
每次从IoC容器获取Java对象都是新的对象;
在application.xml文件中配置如下信息
<bean name="student" class="com.zzu.vo.Student" lazy-init="false" scope="prototype"></bean>
Test中代码不变,得到下边结果,创建了不同的对象
scope=“request”:
每次HTTP请求都会创建一个新的Bean,该作用域只适用于WebApplicationContext环境;
scope=“session”:
每次有新的会话都会创建一个新的Bean,该作用域只适用于WebApplicationContext环境;