注解形势:通过@Scope注解控制作用域,默认使用单实例模式,可修改为多实例模式
1 1 /** 2 2 * Specifies the name of the scope to use for the annotated component/bean. 3 3 * <p>Defaults to an empty string ({@code ""}) which implies 4 4 * {@link ConfigurableBeanFactory#SCOPE_SINGLETON SCOPE_SINGLETON}. 5 5 * @since 4.2 6 6 * @see ConfigurableBeanFactory#SCOPE_PROTOTYPE prototype 7 7 * @see ConfigurableBeanFactory#SCOPE_SINGLETON singleton 8 8 * @see org.springframework.web.context.WebApplicationContext#SCOPE_REQUEST request 9 9 * @see org.springframework.web.context.WebApplicationContext#SCOPE_SESSION session 1010 * @see #value 1111 * 1212 * prototype:多实例的 1313 * singleton:单实例的(默认)单实例启动在ioc容器启动会调用方法创建对象放入到ioc容器中,以后每次获取直接从ioc容器中拿,都是之前创建好的对象 1414 * request:同一次请求创建一个实例 多实例情况下 ,ioc启动时并不会调用方法创建对象放到容器中,而是没次获取对象时创建对象,每次获取都是不同的实例 1515 * session:同一个session创建一个实例 1616 */ 1717 @Scope(value="prototype") //控制作用域 1818 @Bean("persion") 1919 public Persion persion() { 2020 return new Persion("zhangsan",20); 2121 }
同理xml使用:
11 <bean id="persion" class="com.test.bean.Persion" scope="singleton"> 22 <property name="age" value="18"></property> 33 <property name="name" value="zhangsan"></property> 44 </bean>
测试类:bean==bean2 相等说明是同一个示例,不相等 说明是多个示例
1 1 @Test 2 2 public void test02() { 3 3 AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext( 4 4 MainConfig2.class); 5 5 6 6 String[] definitionNames = applicationContext.getBeanDefinitionNames();// 获取spring装配的bean 7 7 8 8 for (String name : definitionNames) { 9 9 System.out.println(name); 1010 } 1111 System.out.println("ioc容器创建完成。。。"); 1212 Object bean=applicationContext.getBean("persion"); 1313 Object bean2=applicationContext.getBean("persion"); 1414 System.out.println(bean==bean2); 1515 1616 } 1717