程序如下
------------------------------------------------------------------------------------
public class Mother { public Mother(){

System.out.println("Mother object has been instance");

}

}--------------------------------------------------------------------------------------
public class People { private Mother mother;

public People(){

System.out.println("People Object has been instance");

}

public static int sum = 0;

public void sayHello(){
System.out.println(sum);
sum ++;
}

public void setMother(Mother mother){

this.mother = mother;

}

}
-------------------------------------------------------------------public static void main(String[] args){

ApplicationContext context = new ClassPathXmlApplicationContext("apptest.xml");

People people = (People)context.getBean("people");
people.sayHello();

ApplicationContext context2 = new FileSystemXmlApplicationContext("D://tempSpace//springPro//bin//apptest.xml");
people = (People)context2.getBean("people");
people.sayHello();
}---------------------------------------------------------------------
<beans> <bean id="people" class="com.springinaction.chapter02.applicationcontext.People" >
<property name="mother">
<ref bean="mother"/>
</property>
</bean>

<bean id="mother" class="com.springinaction.chapter02.applicationcontext.Mother" /></beans>-----------------------------------------------------------------
输出结果为:
People Object has been instance
Mother object has been instance
0
People Object has been instance
Mother object has been instance
1我的问题是:
1.bean默认为单例,为什么不同的context装载会出现两次new的情况呢?
2.如果不同context装载是产生多个实例,那么为什么People的静态变量int会是不同的值?,不是应该都是0吗?

解决方案 »

  1.   

    单例是在单容器下说的 你这启动了2个app。 
    ApplicationContext context = new ClassPathXmlApplicationContext("apptest.xml");People people = (People)context.getBean("people");
    people.sayHello();ApplicationContext context2 = new FileSystemXmlApplicationContext("D://tempSpace//springPro//bin//apptest.xml");
    people = (People)context2.getBean("people");
    people.sayHello();
      

  2.   

    对的,是有两个app,那么多个实例是可以理解的,但是为什么静态变量是累加,而不是都是0呢?打印的结果应该是
    People Object has been instance
    Mother object has been instance
    0
    People Object has been instance
    Mother object has been instance
    0
      

  3.   

    静态是静态,单例是单例
    静态变量是跟随class的,与类无关,无论你建立了几个object,静态变量还是一个.