bean作用域
scope="singleton" 单例模型
scope="singleton":默认值,IoC容器中只存在一个Java类对象,此时Java对象为单例,即每次从IoC容器获取的Java对象都是同一个;
代码如下:
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");//创建集合(IOC容器),并将application.xml中bean放在容器中 Student stu =(Student) applicationContext.getBean("student");//从IOC容器中获取Bean对象 System.out.println(stu); stu =(Student)applicationContext.getBean("student"); System.out.println(stu); applicationContext.close(); } }
运行结果:
scope="prototype"多例模型
scope="prototype":每次从IoC容器获取Java对象都是新的对象;
运行结果:
scope="request"
scope="request":每次HTTP请求都会创建一个新的Bean,该作用域只适用于WebApplicationContext环境;
scope="session"
scope="session":每次有新的会话都会创建一个新的Bean,该作用域只适用于WebApplicationContext环境;