Spring学习笔记之三“scope” --bean范围


三、spring Bean的作用域:
 
scope可以取值: 
 * singleton:每次调用getBean的时候返回相同的实例
 * prototype:每次调用getBean的时候返回不同的实例

1、applicationContext-beans.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:aop="http://www.springframework.org/schema/aop"
      xmlns:tx="http://www.springframework.org/schema/tx"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
 <!--
 <bean id="bean1" class="com.bjsxt.spring.Bean1" scope="prototype"/>
  设置成scope="prototype",下面测试代码输出bean11!=bean12,反之scope="singleton",永远只生成一个实例-->
 <bean id="bean1" class="com.bjsxt.spring.Bean1" scope="singleton"/>
</beans>

2、测试代码
package com.bjsxt.spring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.TestCase;

public class ScopeTest extends TestCase {
 
 private BeanFactory factory;
 
 @Override
 protected void setUp() throws Exception {
  factory = new ClassPathXmlApplicationContext("applicationContext-*.xml"); 
 }

 public void testScope1() {
  Bean1 bean11 = (Bean1)factory.getBean("bean1");
  Bean1 bean12 = (Bean1)factory.getBean("bean1");
  if (bean11 == bean12) {
   System.out.println("bean11==bean12");
  }else {
   System.out.println("bean11!=bean12");
  }
 }
}

你可能感兴趣的:(spring,AOP,bean,xml,prototype)