@Scope(作用域)

@Scope

@Scope注解是springIoc容器中的一个作用域,在 Spring IoC 容器中具有以下几种作用域:基本作用域singleton(单例)prototype(多例),Web 作用域(reqeust、session、globalsession),自定义作用域

xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
    <bean id="Person" class="cn.jbit.bean.Person" scope="singleton">
        <property name="age" value="18"></property>
        <property name="name" value="zhangsan"></property>
    </bean>
</beans>

注解

@Configuration
public class MainConfig2 {
//    默认是单实例的
    /**
     * ConfigurableBeanFactory#SCOPE_PROTOTYPE  [prototype]
  	 * ConfigurableBeanFactory#SCOPE_SINGLETON  [singleton]
     * @return
     * prototype:多实例的: ioc容器启动并不会去调用方法创建对象放到IOC容器中
     * 每次获取的时候才会调用方法创建对象
     * singleton:单实例的(默认的): ioc容器启动会调用方法创建对象放到IOC容器中
     * 以后每次获取就是直接从容器(map.get())中拿
     * 懒加载
     *     单实例bean,默认在容器启动的时候创建对象
     *     懒加载:容器启动不创建对象,第一次使用(获取)Bean创建对象,并初始化
     */
//    @Scope("prototype")   //调整作用域
    @Bean("person")
    @Lazy  //懒加载
    public Person person(){
        System.out.println("给容器中添加person...");
        return new Person("张三",11);
    }
}
    @Test
    public void test04(){
        ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig2.class);
        String[] beanDefinitionNames = app.getBeanDefinitionNames();//获取Bean定义名称
        for (String name : beanDefinitionNames) {
            System.out.println(name);
        }
        /**
         *  singleton:true
         *  prototype: false
         */
        System.out.println("ioc容器创建完成...");
        Object bean = app.getBean("person");
        Object bean2 = app.getBean("person");
        System.out.println(bean==bean2);
    }
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值