求解,关于spring装载bean时单例的疑惑

tragedy 2011-01-10 12:38:34
程序如下
------------------------------------------------------------------------------------
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吗?
...全文
102 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
liufeng0209 2011-01-10
  • 打赏
  • 举报
回复
静态是静态,单例是单例
静态变量是跟随class的,与类无关,无论你建立了几个object,静态变量还是一个.
tragedy 2011-01-10
  • 打赏
  • 举报
回复
对的,是有两个app,那么多个实例是可以理解的,但是为什么静态变量是累加,而不是都是0呢?打印的结果应该是
People Object has been instance
Mother object has been instance
0
People Object has been instance
Mother object has been instance
0
sustbeckham 2011-01-10
  • 打赏
  • 举报
回复
单例是在单容器下说的 你这启动了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();
liufeng0209 2011-01-10
  • 打赏
  • 举报
回复
你有2个ApplicationContext吧

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧