Singleton Scope And Prototype Scope : Singleton « Spring « Java Tutorial






File: context.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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
                http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/util
                http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="singleMe" class="java.lang.String" scope="singleton">
        <constructor-arg type="java.lang.String" value="Singleton"/>
    </bean>

    <bean id="prototypeMe" class="java.lang.String" scope="prototype">
        <constructor-arg type="java.lang.String" value="Prototype"/>
    </bean>



</beans>

File: Main.java

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class Main {
  private static void compare(final BeanFactory factory, final String beanName) {
    String b1 = (String)factory.getBean(beanName);
    String b2 = (String)factory.getBean(beanName);
    System.out.println("Bean b1=" + b1 + ", b2=" + b2);
    System.out.println("Same?  " + (b1 == b2));
    System.out.println("Equal? " + (b1.equals(b2)));
}

public static void main(String[] args) {
    BeanFactory factory = new XmlBeanFactory(
                        new ClassPathResource("context.xml"));
    compare(factory, "singleMe");
    compare(factory, "prototypeMe");
    compare(factory, "requestMe");
}
}
  Download:  Spring-SingletonScopeAndPrototypeScope.zip( 2,599 k)








28.11.Singleton
28.11.1.Prototype Singleton
28.11.2.BeanFactory PreInstantiate Singletons Integration
28.11.3.Spring Prototype
28.11.4.Singleton Scope And Prototype Scope