按照spring官网说明,分成如下五种
| Scope | Description |
|---|---|
| (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. | |
| Scopes a single bean definition to any number of object instances. | |
| 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 | |
| Scopes a single bean definition to the lifecycle of an HTTP | |
| Scopes a single bean definition to the lifecycle of a | |
| Scopes a single bean definition to the lifecycle of a |
singleton 单例模式 spring默认容器里面的一个对象的实例只有一个
举个栗子:
public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
}
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="person" class="demo.guhong.test04.Person" scope="singleton" name="person2">
<property name="name" value="bitch"/>
</bean>
</beans>
测试:
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("testbeans.xml");
Person person = (Person) context.getBean("person");
Person person2 = (Person) context.getBean("person2");
System.out.println(person == person2);
}
----------------------------------------------------
true
Process finished with exit code 0
prototype 原型模式:每次从容器中取出来的时候,都是新对象
还是上面的Person,修改xml 中bean属性:scope
<bean id="person" class="demo.guhong.test04.Person" scope="prototype" name="person2">
<property name="name" value="bitch"/>
</bean>
结果:
----------------------------------------------------
false
Process finished with exit code 0
request sessoion application websocket
都是在web中用到各自对应不同情形的bean存活时间段,后续有机会待补充

本文详细解析了Spring框架中Bean的五种作用域:singleton、prototype、request、session及application,探讨了每种作用域下Bean实例的生命周期及应用场景,特别强调了在web环境下各作用域的适用场景。
687

被折叠的 条评论
为什么被折叠?



