Spring Boot Scope范围学习

Spring Boot Scope范围学习

    • Scope的理解
    • SingletonService
    • ProptotypeService
    • ScopeConfig 配置类的编写
    • Main的编写
    • 运行结果

Scope的理解

顾明思意,Scope就是范围的意思,工程分为普通项目与web项目,所以范围就分成了两大类。
1、Singleton:一个Spring容器只有一个Bean实例。
2、Prototype:每次调用都会新建一个Bean案列。
3、Request:web项目中,会给每一个http request新建一个Bean实例。
4、Session:web项目中,会给每一个http session新建一个Bean案列。

SingletonService

1
2
3
4
5
6
7
8
9
10
package com.springboot.scope;

import org.springframework.stereotype.Service;

@Service
//默认状态下是Singleton
public class SingletonService
{
   
}

ProptotypeService

1
2
3
4
5
6
7
8
9
10
11
package com.springboot.scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("prototype")
//注释为Proptotype
public class ProptotypeService {

}

ScopeConfig 配置类的编写

1
2
3
4
5
6
7
8
9
10
11
package com.springboot.scope;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.springboot.scope")
//配置类扫描指定路径
public class ScopeConfig {

}

Main的编写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.springboot.scope;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main
{
    public static void main(String ager[])
    {
        AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext(ScopeConfig.class);
       
        ProptotypeService p1=context.getBean(ProptotypeService.class);
        ProptotypeService p2=context.getBean(ProptotypeService.class);
       
        SingletonService s1=context.getBean(SingletonService.class);
        SingletonService s2=context.getBean(SingletonService.class);
        if(p1.equals(p2))
        {
            System.out.println("p1==p2");
        }
        if(s1.equals(s2))
        {
            System.out.println("s1==s2");
        }
        context.close();
    }
}

运行结果

在这里插入图片描述
这里显示s1=s2表明单项模式中只可以存在一个实例,故p1!=p2。