当前位置: 首页 > 工具软件 > scope > 使用案例 >

@Scope(作用域)

夏英发
2023-12-01

@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);
    }
 类似资料: