【发布时间】:2016-05-11 01:46:07
【问题描述】:
我的 Employee 类是 spring.xml 中定义的单例
public class Employee{
private Vehicle vehicle;
public Vehicle getVehicle() {
return vehicle;
}
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
}
我有类 Vehicle,它是 spring.xml 中定义的原型
public class Vehicle {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
下面是spring.xml
<bean id="employee" class="com.example.factory.Employee">
<property name="vehicle" ref="vehicle"></property>
</bean>
<bean id="vehicle" class="com.example.factory.Vehicle" scope="prototype">
<property name="name" value="car"></property>
<aop:scoped-proxy />
</bean>
现在我知道 spring 将为车辆创建代理。每次我在员工对象上调用 getVehicle() 时,我都会得到 Vehicle 的新对象。但是在 getVehicle() 方法中,我没有创建 Vehicle 的新对象,并且根据我的理解,spring 没有为 Employee 对象创建代理。所以有人请让我详细了解内部发生了什么以及 getVehicle() 是如何工作的?
【问题讨论】:
-
实际上
getVehicle()总是返回相同的对象,它实际上是实际Vehicle实例的代理。对于您在Vehicle上执行的每个方法调用,您将获得一个新实例,因为这就是您告诉它对作用域代理和scope=prototype执行的操作。基本上,作用域代理对scope=prototype没有意义,仅对request和session作用域(以及默认情况下未提供的其他一些)。 -
如果
getVehicle()总是返回同一个对象,那么为什么在执行System.out.println(getVehicle())这个语句时每次都会产生不同的hashcode?span> -
因为它返回一个代理而不是实际对象,所以代理总是相同的。
hashCode方法被传递给实际的底层对象,(基本上使用hashCode来检查它是否是同一个对象并不是一件好事,尤其是在使用代理时)。