java - 如果我们通过 aop 作用域代理将原型(prototype) bean 注入(inject)到单例 bean 中,getter 如何工作(单例 Bean)?

标签 java spring proxy

我有类 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 实例时,您都会获得一个新的实例。这可能通过两种方式发生:

  1. 您向 Spring 请求一个 Vehicle bean
  2. Spring 将 Vehicle Autowiring 到 Employee bean。这种情况只会发生一次,因为 Employee 是单例。所以如果这是唯一的 Vehicle 的使用方式,它也可能是一个单例。

参见this page以获得更详细的解释。

关于java - 如果我们通过 aop 作用域代理将原型(prototype) bean 注入(inject)到单例 bean 中,getter 如何工作(单例 Bean)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35150345/

相关文章:

java - 如何将两个字符串与随机位置android结合起来

java - libgdx box2d body - 为什么到达接触点位置后 body 会摇晃?

java - 如何打开这个Java项目中的可执行文件?我已经尝试打开所有 .jar 文件

java - 在 Spring 中处理上下文

docker - nginx 后面的 docker 注册表错误,推拉

video - 为什么在使用 youtube-dl 设置代理参数时无法下载视频标题?

java - 为什么DataNode无法下载文件?

java - 将 Resteasy 与 javassist 一起使用?

spring - 在 Angular 5 中接收 Flux SSE

haskell - 代理、类型级别符号和 JSON