我有类 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 中定义的原型(prototype)
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() 时,我都会得到车辆的新对象。但是在 getVehicle() 方法中,我没有创建 Vehicle 的新对象,并且根据我的理解,spring 没有为 Employee 对象创建代理。所以有人请让我详细了解内部发生的情况以及 getVehicle() 是如何工作的?
最佳答案
每次调用 getVehicle() 时,您不会获得一个新的 Vehicle 实例。每次 Spring 必须提供一个新的 Vehicle 实例时,您都会获得一个新的实例。这可能通过两种方式发生:
- 您向 Spring 请求一个 Vehicle bean
- Spring 将 Vehicle Autowiring 到 Employee bean。这种情况只会发生一次,因为 Employee 是单例。所以如果这是唯一的 Vehicle 的使用方式,它也可能是一个单例。
参见this page以获得更详细的解释。
关于java - 如果我们通过 aop 作用域代理将原型(prototype) bean 注入(inject)到单例 bean 中,getter 如何工作(单例 Bean)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35150345/