日期:2014-05-19  浏览次数:20625 次

SSH整合之后,组件的hashCode的问题
Action默认用的是prototype模式,而Dao、service默认利用的是single模式,请见以下代码:
Action:

@Action("/tagTest")
public String tagTest() throws Exception{
System.out.println("ActionCode:"+hashCode());
System.out.println("serviceCode1:"+studentManager.hashCode());
studentManager.queryById(3);
System.out.println("----");
return "tagTest";
}

@Action("/testList")
public String testList() throws Exception{
System.out.println("ActionCode:"+hashCode());
System.out.println("serviceCode1:"+studentManager.hashCode());
//action不一样(原型模式),但是dao、service的hashCode却一样(单例模式)
//action里边service的hashCode、service自己的this.hashCode()却不一样?
studentManager.queryById(3);
System.out.println("----");
return "tagTest";
}

Service:

public Student queryById(int id) throws Exception{
System.out.println("daoCode:"+studentDao.hashCode());
System.out.println("serviceCode2:"+hashCode());
return studentDao.queryByID(id);
}


执行Action的两个函数之后,有如下输出:
ActionCode:5518985
serviceCode1:105906061
false
daoCode:20236598
serviceCode2:13142182
----
ActionCode:29505482
serviceCode1:105906061
false
daoCode:20236598
serviceCode2:13142182
----

我就奇怪了,service层是单例模式,为啥serviceCode1与serviceCode2不一样呢?
service action dao 单例?? 原型

------解决方案--------------------
定义俩对象,比较下是否相同,如果俩对象相同并且hashcode也一样,再说。
------解决方案--------------------
说明俩不是一个对象,当然hashcode不同了。。。
------解决方案--------------------
单例模式是只向外提供一个对象,每次创建的都是同一个对象。sm==this不要这样比较用equals和hashcode比较看看结果是true还是false
------解决方案--------------------
引用:
引用:
说明俩不是一个对象,当然hashcode不同了。。。
和“单例模式”冲突了么?


不冲突,spring注入的属性其实是使用的代理方式实现的,所以action中的service对象是代理对象,而service内部的hashcode才是自身的。别忘记代理哦