Java/Spring/IoC Singleton
Версия от 18:01, 31 мая 2010; (обсуждение)
Achieving Singleton in IoC
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: beans.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- non-singleton examples -->
<bean id="nonSingleton" class="java.lang.String" singleton="true">
<constructor-arg>
<value>Value</value>
</constructor-arg>
</bean>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class NonSingleton {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"build/beans.xml"));
String s1 = (String)factory.getBean("nonSingleton");
String s2 = (String)factory.getBean("nonSingleton");
System.out.println("Identity Equal?: " + (s1 ==s2));
System.out.println("Value Equal:? " + s1.equals(s2));
System.out.println(s1);
System.out.println(s2);
}
}
Non Singleton
/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: beans.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- non-singleton examples -->
<bean id="nonSingleton" class="java.lang.String" singleton="false">
<constructor-arg>
<value>Value</value>
</constructor-arg>
</bean>
</beans>
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class NonSingleton {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"build/beans.xml"));
String s1 = (String)factory.getBean("nonSingleton");
String s2 = (String)factory.getBean("nonSingleton");
System.out.println("Identity Equal?: " + (s1 ==s2));
System.out.println("Value Equal:? " + s1.equals(s2));
System.out.println(s1);
System.out.println(s2);
}
}