首页 > 代码库 > Spring scope 配置

Spring scope 配置

Scope 描述的是 Spring 容器如何新建Bean的实例,Spring的Scope有以下几种,通过@Scope来注解实现:

1. Singleton: 一个Spring容器中只有一个Bean的实例。

2. Prototype: 每次调用新建一个Bean的实例。

3. Request: Web项目中,给每一个http request新建一个Bean的实例。

4. Session: Web项目中,给每一个http session新建一个Bean的实例。

5. GlobalSession: 给每一个global http session新建一个Bean实例。

 

例: singleton 和 Prototype 区别:

1. 编写 Singleton 的 Bean类

package com.cz.scope;

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

/**
 * Created by Administrator on 2017/5/11.
 */
@Service
public class DemeSingletonService {
}

 

 

2. 创建 Prototyped 的 Bean类

package com.cz.scope;

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

/**
 * Created by Administrator on 2017/5/11.
 */
@Service
@Scope("prototype")
public class DemoPrototypeService {

 

 

3. 创建 Scope java配置类

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

/**
 * Created by Administrator on 2017/5/11.
 */
@Configuration
@ComponentScan("com.cz.scope")
public class ScopeConfig {
}

 

 

4. 创建测试类

 

package com.cz.scope;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * Created by Administrator on 2017/5/11.
 */
public class TestScope {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ScopeConfig.class);
        DemeSingletonService s1 = context.getBean(DemeSingletonService.class);
        DemeSingletonService s2 = context.getBean(DemeSingletonService.class);

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

        System.out.println("s1 equals s2 = " + s1.equals(s2));
        System.out.println("p1 equals p2 = " + p1.equals(p2));
    }
}

 

 

5. 执行结果,可以看出 single创建的两次对象是相同的,而prototype创建的两次对象是不同的

技术分享

 

Spring scope 配置