@Scope-作用域调整

prototype多实例

配置类

// 配置类注解 告诉spring这是个配置
@Configuration
public class MyConfig {
    
    /**
     * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_PROTOTYPE prototype
     * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_SINGLETON singleton
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST  request
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION     sesssion
     * prototype:多实例的:ioc容器启动并不会去调用方法创建对象放在容器中。
     *                     每次获取的时候才会调用方法创建对象;
     * singleton:单实例的(默认值):ioc容器启动会调用方法创建对象放到ioc容器中。
     *             以后每次获取就是直接从容器(map.get())中拿,
     * request:同一次请求创建一个实例
     * session:同一个session创建一个实例
     */
    @Scope("prototype")
    @Bean
    public Pet configName(){
        return new Pet("小猫",2);
    }
}

输出

 @Test
    public void test1() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
        String[] beanNamesForType = applicationContext.getBeanDefinitionNames();
        for (String name : beanNamesForType) {
            System.out.println(name);
        }
        Object configName = applicationContext.getBean("configName");
        Object configName1 = applicationContext.getBean("configName");
        System.out.println(configName == configName1);
    }

输出结果

singleton单实例

// 配置类注解 告诉spring这是个配置
@Configuration
public class MyConfig {

    /**
     * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_PROTOTYPE prototype
     * @see org.springframework.beans.factory.config.ConfigurableBeanFactory#SCOPE_SINGLETON singleton
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST  request
     * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION     sesssion
     * prototype:多实例的:ioc容器启动并不会去调用方法创建对象放在容器中。
     *                     每次获取的时候才会调用方法创建对象;
     * singleton:单实例的(默认值):ioc容器启动会调用方法创建对象放到ioc容器中。
     *             以后每次获取就是直接从容器(map.get())中拿,
     * request:同一次请求创建一个实例
     * session:同一个session创建一个实例
     */
    @Scope("singleton")
    @Bean
    public Pet configName(){
        return new Pet("小猫",2);
    }
}

输出

输出结果

posted @ 2022-06-02 09:58  Dabo丶  阅读(21)  评论(0编辑  收藏  举报