spring中@Scope控制作用域

  注解形势:通过@Scope注解控制作用域,默认使用单实例模式,可修改为多实例模式

 1 /**
 2      * Specifies the name of the scope to use for the annotated component/bean.
 3      * <p>Defaults to an empty string ({@code ""}) which implies
 4      * {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}.
 5      * @since 4.2
 6      * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE prototype
 7      * @see ConfigurableBeanFactory#SCOPE_SINGLETON singleton
 8      * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST request
 9      * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION session
10      * @see #value
11      * 
12      * prototype:多实例的
13      * singleton:单实例的(默认)单实例启动在ioc容器启动会调用方法创建对象放入到ioc容器中,以后每次获取直接从ioc容器中拿,都是之前创建好的对象
14      * request:同一次请求创建一个实例 多实例情况下 ,ioc启动时并不会调用方法创建对象放到容器中,而是没次获取对象时创建对象,每次获取都是不同的实例
15      * session:同一个session创建一个实例
16      */
17     @Scope(value="prototype") //控制作用域
18     @Bean("persion")
19     public Persion persion() {
20         return new Persion("zhangsan",20);
21     }

同理xml使用:

1 <bean id="persion" class="com.test.bean.Persion" scope="singleton">
2         <property name="age" value="18"></property>
3         <property name="name" value="zhangsan"></property>
4     </bean>

 测试类:bean==bean2 相等说明是同一个示例,不相等 说明是多个示例

 1 @Test
 2     public void test02() {
 3         AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
 4                 MainConfig2.class);
 5 
 6         String[] definitionNames = applicationContext.getBeanDefinitionNames();// 获取spring装配的bean
 7 
 8         for (String name : definitionNames) {
 9             System.out.println(name);
10         }
11         System.out.println("ioc容器创建完成。。。");
12         Object bean=applicationContext.getBean("persion");
13         Object bean2=applicationContext.getBean("persion");
14         System.out.println(bean==bean2);
15         
16     }
17     

 

posted @ 2019-01-25 14:30  东道东道广泛  阅读(742)  评论(0编辑  收藏  举报