首页 > 代码库 > Spring Boot教程4——@Scope注解

Spring Boot教程4——@Scope注解

Scope描述Spring容器如何新建Bean的实例,有以下几种:
1.Singleton:一个Spring容器中只有一个Bean的实例,此为Spring的默认配置,全容器共享一个实例;
2.Prototype:每次调用新建一个Bean的实例;
3.Request:Web项目中,给每一个http request新建一个Bean实例;
4.Session:Web项目中,给每一个http session新建一个Bean实例;
5.GlobalSession:这个只在portal应用中有用,给每一个global http session新建一个Bean实例;
另外,在Spring Batch中还有一个Scope是使用@StepScope,将在批处理一节介绍这个Scope。

@Service
@Scope("prototype")//如果不声明就相当于采用默认值@Scope("singleton")
public class DemoPrototypeService{
}

示例

1>.编写Singleton的Bean

package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.stereotype.Service;

@Service //默认为Singleton,相当于@Scope("singleton")
public class DemoSingletonService {

}

2>.编写Prototype的Bean

package com.wisely.highlight_spring4.ch2.scope;

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

@Service
@Scope("prototype")//声明Scope为Prototype
public class DemoPrototypeService {

}

3>.配置类

package com.wisely.highlight_spring4.ch2.scope;

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

@Configuration
@ComponentScan("com.wisely.highlight_spring4.ch2.scope")
public class ScopeConfig {

}

4>.运行

package com.wisely.highlight_spring4.ch2.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context =
                new AnnotationConfigApplicationContext(ScopeConfig.class); 
        DemoSingletonService s1 = context.getBean(DemoSingletonService.class);
        DemoSingletonService s2 = context.getBean(DemoSingletonService.class);

        DemoPrototypeService p1 = context.getBean(DemoPrototypeService.class);
        DemoPrototypeService p2 = context.getBean(DemoPrototypeService.class);

        System.out.println("s1与s2是否相等:"+s1.equals(s2));
        System.out.println("p1与p2是否相等:"+p1.equals(p2));
        
        context.close();
    }
}

Spring Boot教程4——@Scope注解