spring_scope


Spring Beanの役割ドメイン:
scopeは値を取ることができます.
*singleton:getBeanが呼び出されるたびに同じインスタンスが返されます.
*prototype:getBeanが呼び出されるたびに異なるインスタンスが返されます
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="singleton"/>
	 -->
	<bean id="bean1" class="com.bjsxt.spring.Bean1" scope="prototype"/> 
</beans>

Bean1.java
package com.bjsxt.spring;

public class Bean1 {
}

ScopeTest.java
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");
		}
	}
}