1、使用scope属性配置bean的作用域
2、scope属性值:
(1)singleton:容器初始化时创建bean实例,整个容器生命周期里,只创建一个bean实例 (scope默认值)
(2)prototype:容器初始化时不创建bean实例,在请求的时候都会创建一个bean实例 (如:整合struts 2 的action时,就需要用到这个)
(3)request :容器初始化时不创建bean实例,在Http请求时都会创建一个bean实例(适用于WebApplicationContext环境中)
(4)session :容器初始化时创建一个bean实例,遇到同一个Http的session时,session共享一个bean,不同http的session使用不同bean (适用于WebApplicationContext环境中)
3、文件:
①TestScope.java:测试类
②ScopenBean.java:数据模型
③scopenCopntext.xml:配置文件
4、TestScope.java
package com.demo.sshtest.scope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestScope {
public static void main(String[] args) {
scope();
}
public static void scope(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("scopeContext.xml");
ScopeBean scopeBean = (ScopeBean)applicationContext.getBean("scopebean");
System.out.println(scopeBean);
ScopeBean scopeBean2 = (ScopeBean)applicationContext.getBean("scopebean");
System.out.println(scopeBean2);
System.out.println(scopeBean==scopeBean2);
}
}
5、ScopenBean.java
package com.demo.sshtest.scope;
public class ScopeBean {
private Integer id;
private String name;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "ScopeBean [id=" + id + ", name=" + name + ", password=" + password + "]";
}
}
6、scopenCopntext.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
<!--
bean的作用域
1、使用scope属性配置bean的作用域
2、scope属性值:
(1)singleton:容器初始化时创建bean实例,整个容器生命周期里,只创建一个bean实例 (scope默认值)
(2)prototype:容器初始化时不创建bean实例,在请求的时候都会创建一个bean实例 (如:整合struts 2 的action时,就需要用到这个)
(3)request :容器初始化时不创建bean实例,在Http请求时都会创建一个bean实例(适用于WebApplicationContext环境中)
(4)session :容器初始化时创建一个bean实例,遇到同一个Http的session时,session共享一个bean,不同http的session使用不同bean (适用于WebApplicationContext环境中)
-->
<bean id="scopebean" class="com.demo.sshtest.scope.ScopeBean" scope="singleton">
<property name="id" value="1"></property>
<property name="name" value="12312"></property>
<property name="password" value="13e12e12"></property>
</bean>
</beans>
7、项目目录
8、demo
https://download.csdn.net/download/qq_22778717/10470322