Java/Spring/Singleton

Материал из Java эксперт
Версия от 06:16, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

BeanFactory PreInstantiate Singletons Integration

       
File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
   <bean id="instantiationCounterClass"
      class="InstantiationCounterClass"/>
</beans>

File: Main.java
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) throws Exception {
    ConfigurableListableBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
        "context.xml"));
    System.out.println(InstantiationCounterClass.getNumberOfInstantiations());
    beanFactory.preInstantiateSingletons();
    System.out.println(InstantiationCounterClass.getNumberOfInstantiations());
  }
}
class InstantiationCounterClass {
  private static AtomicInteger instantiationCounter = new AtomicInteger(0);
  public static int getNumberOfInstantiations() {
    return instantiationCounter.get();
  }
  public InstantiationCounterClass() {
    instantiationCounter.incrementAndGet();
  }
}





Prototype Singleton

File: context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
   <bean id="primeIterator"
      class="PrimeIterator" singleton="false">
      <property name="start" value="1000"/>
   </bean>
</beans>

File: Main.java
import java.util.Properties;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) throws Exception {
    BeanFactory beanFactory =
      new XmlBeanFactory(
         new ClassPathResource(
            "context.xml"
         )
      );
   PrimeIterator primeNumber1 = (PrimeIterator)beanFactory.getBean("primeIterator");
   PrimeIterator primeNumber2 = (PrimeIterator)beanFactory.getBean("primeIterator");
   System.out.println(primeNumber1.getNextPrime());
   System.out.println(primeNumber2.getNextPrime());
 }
}
class PrimeIterator {
  int start = -1;
   public int getNextPrime() {
       return start;
  }
  public int getStart() {
    return start;
  }
  public void setStart(int start) {
    this.start = start;
  }
}