【Spring注解】@Scope 作用域和@Lazy懒加载

2.@Scope 作用域和@Lazy懒加载

@Scope来表示注册对象的作用域。

@Scope的四种类型

//多例模式,只有在使用类时才注册对象
ConfigurableBeanFactory#SCOPE_PROTOTYPE 
//单例模式(默认),容器初始化时就注册对象,不过可以通过@Lazy注解来实现懒加载
ConfigurableBeanFactory#SCOPE_SINGLETON
//web的requerst域(不常用)
org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST
//web的Session域(不常用)
org.springframework.web.context.WebApplicationContext#SCOPE_SESSION
@Configuration
public class ScopeConfig {
    @Bean
    @Scope("prototype")
    public Person person(){
        System.out.println("向容器中注册Person对象。。。。");
        return new Person("gaoyuzhe ",12);
    }
}
public class ScopeConfigTest {
    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(ScopeConfig.class);

    /**
     * 遍历匹配的组件名称
     * @param annotationConfigApplicationContext 注解上下文
     */
    private void printClassName(AnnotationConfigApplicationContext annotationConfigApplicationContext){
        String[] beanDefinitionNames = annotationConfigApplicationContext.getBeanDefinitionNames();
        for (int i = 0; i < beanDefinitionNames.length; i++) {
            System.out.println("匹配的类"+beanDefinitionNames[i]);
        }
    }
    @Test
    public void person() {
        printClassName(annotationConfigApplicationContext);
    }
}

prototype未调用

调用Person对象

@Test
        public void person() {
            printClassName(annotationConfigApplicationContext);
            Person person1 = annotationConfigApplicationContext.getBean(Person.class);
            System.out.println(person1);
            Person person2 = annotationConfigApplicationContext.getBean(Person.class);
            System.out.println(person2);
            System.out.println(person1 ==person2);
        }

调用Person对象

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值