bean的作用域
bean的作用域
理论知识
bean的作用域有6种类型,官网的描述在这里
Scope | Description |
---|---|
singleton | (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. |
prototype | Scopes a single bean definition to any number of object instances. |
request | Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. |
session | Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. |
application | Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext. |
websocket | Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext. |
核心的两种作用域是singleton和prototype
singleton 即单例,指所有获取的该实例均为同一个实例
prototype 即原型,指每次获取该实例都会新创建一个
其他4种作用域只能在web开发中使用到
实践
User实体类
package com.kuangstudy.di;
/**
* 功能描述
*
* @since 2022-06-25
*/
public class User {
private String name;
private String age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public User() {
}
public User(String name, String age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="u1" class="com.kuangstudy.di.User" p:age="20" p:name="xiaoming" scope="singleton"></bean>
<bean id="u2" class="com.kuangstudy.di.User" c:age="30" c:name="xiaohong" scope="prototype"></bean>
</beans>
测试类
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.kuangstudy.di.Student;
import com.kuangstudy.di.User;
/**
* 功能描述
*
* @since 2022-06-25
*/
public class Test01 {
@Test
public void test2() {
ApplicationContext context = new ClassPathXmlApplicationContext("beans1.xml");
User u1_1 = context.getBean("u1", User.class);
User u1_2 = context.getBean("u1", User.class);
System.out.println(u1_1 == u1_2);
User u2_1 = context.getBean("u2", User.class);
User u2_2 = context.getBean("u2", User.class);
System.out.println(u2_1 == u2_2);
}
}
结果
true
false