Spring系列(四):@Scope注解用法介绍


今天给大家分享Spring中@Scope注解的用法,希望对大家能有所帮助!
- @Scope 定义以及作用
@Scope注解主要作用是调节Ioc容器中的作用域,在Spring IoC容器中主要有以下五种作用域:基本作用域:singleton(单例)、prototype(多例);Web 作用域(reqeust、session、globalsession),自定义作用域。
- @Scope 作用域类型
2.1 @Scope("singleton")
单实例属于默认作用域,IOC容器启动的时候就会调用方法创建对象,以后每次获取都是从Spring容器当中拿同一个对象(map当中)。
2.2 @Scope("prototype")
多实例,在IOC容器启动创建的时候,并不会直接创建对象放在容器中去,当你需要调用的时候,才会从容器当中获取该对象然后进行创建。
2.3 @Scope("request")
同一个请求创建一个实例
2.4 @Scope("session")
同一个session创建一个实例
2.5 @Scope("globalsession")
同一个globalsession创建一个实例
- 示例演示
3.1 新建Person.java
package com.spring.bean;
public class Person {
private String name;
private Integer age;
private String address;
public Person(String name, Integer age, String address) {
this.name = name;
this.age = age;
this.address = address;
public Person() {
public String getName() {
return name;
public void setName(String name) {
this.name = name;
public Integer getAge() {
return age;
public void setAge(Integer age) {
this.age = age;
public String getAddress() {
return address;
public void setAddress(String address) {
this.address = address;
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
", address='" + address + '\'' +
3.2 新建配置类 TestScopeConfig.java
package com.spring.config;
import com.spring.bean.Person;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
@Configuration
public class TestScopeConfig {
@Bean
@Scope("singleton")
//@Scope("prototype")
public Person person() {
System.out.println("容器添加Person对象......");
return new Person("小孙", 28, "西安");
}
3.3 新建测试类 TestScope.java
package com.spring.test;
import com.spring.bean.Person;
import com.spring.config.TestBeanConfig;
import com.spring.config.TestScopeConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestScope {
public static void main(String[] args) {
//配置文件方式
AnnotationConfigApplicationContext annotationContext = new AnnotationConfigApplicationContext(TestScopeConfig.class);
Object person1 = annotationContext.getBean("person");
Object person2 = annotationContext.getBean("person");
System.out.println(person1);
System.out.println(person2);
boolean flag = person1 == person2;
if (flag) {
System.out.println("是同一个对象");
} else {
System.out.println("不是同一个对象");
}
4、输出效果
4.1 @Scope("prototype")
输出结果:
容器添加Person对象......
Person{name='小孙', age='28', address='西安'}
Person{name='小孙', age='28', address='西安'}
是同一个对象
4.2 @Scope("prototype")
输出结果:
容器添加Person对象......