美文网首页
3. Spring4.x Bean的Scope

3. Spring4.x Bean的Scope

作者: 第八号灬当铺 | 来源:发表于2017-08-29 10:45 被阅读0次

    Bean的Scope的简单示例

    通过@Scope指定以下参数值

    Singleton       单例的 (默认配置)
    Prototype       多例的
    Request         web项目中request级别的单例
    Session         web项目中session级别的单例
    
    GlobalSession   portal应用(不知道是啥...)
    
    1. 新建一个Scope为Singleton的类
    package com.xiaohan.scope;
    
    import org.springframework.stereotype.Service;
    
    @Service
    // 可省略
    // @Scope("singleton")
    public class SingletonService {
    }
    
    1. 新建一个Scope为Prototype的类
    package com.xiaohan.scope;
    
    import org.springframework.context.annotation.Scope;
    import org.springframework.stereotype.Service;
    
    @Service
    @Scope("prototype")
    public class PrototypeService {
    }
    
    1. 配置类
    package com.xiaohan.scope;
    
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    @ComponentScan("com.xiaohan.scope")
    public class ScopeConfig {
    }
    
    1. Main测试
    package com.xiaohan.scope;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    // Bean的Scope
    public class Main {
        public static void main(String[] args) {
            ApplicationContext ac = new AnnotationConfigApplicationContext(ScopeConfig.class);
            SingletonService s1 = ac.getBean(SingletonService.class);
            SingletonService s2 = ac.getBean(SingletonService.class);
            System.err.println(s1.equals(s2));  //true
    
            PrototypeService p1 = ac.getBean(PrototypeService.class);
            PrototypeService p2 = ac.getBean(PrototypeService.class);
            System.err.println(p1.equals(p2));  //false
        }
    }
    

    相关文章

      网友评论

          本文标题:3. Spring4.x Bean的Scope

          本文链接:https://www.haomeiwen.com/subject/fecodxtx.html