• 二、【注解】Spring注解@Scope


    Spring容器中的Bean默认是单例的,可以使用@Scope来设置Bean的类型

    /**
     * @author zhangjianbing
     * time 2020/09/23
     * https://www.zhangjianbing.com
     */
    @Configuration
    public class PersonConfig {
    
        /**
         * String SCOPE_SINGLETON = "singleton";单例
         * String SCOPE_PROTOTYPE = "prototype";多例
         * String SCOPE_REQUEST = "request";一次请求为一个对象
         * String SCOPE_SESSION = "session";一次会话为一个对象
         *
         * 单例:在容器初始化完成之前就已经将Bean实例化了
         * 多例:在使用对象的时候才会去实例化Bean
         */
        @Scope("prototype")
        @Bean
        public Person person() {
            return new Person("张三", 13);
        }
    
    }
    

    测试类:

    public class MainTest {
    
        @Test
        public void m1() {
            ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonConfig.class);
            Person person1 = applicationContext.getBean(Person.class);
            Person person2 = applicationContext.getBean(Person.class);
            System.out.println(person1 == person2);
    
            System.out.println("······容器初始化完成······");
        }
    
    }
    
    测试结果:
    false
    ······容器初始化完成······
    
  • 相关阅读:
    案例(2)-- 线程不安全对象(SimpleDateFormat)
    案例(1)-- OOM异常
    jvm--工具
    死锁的产生以及定位死锁
    TCP--粘包拆包,netty的解决方式
    netty--处理器
    AtomicIntegerFieldUpdater和AtomicInteger
    NIO--ByteBuf
    Pipeline
    吴恩达机器学习笔记(四) —— BP神经网络
  • 原文地址:https://www.cnblogs.com/zhangjianbing/p/13716133.html
Copyright © 2020-2023  润新知