【发布时间】:2020-11-19 02:17:56
【问题描述】:
我最近在 Spring 中发现的一个非常酷且令人难以置信的功能是 self auto-wiring a bean。
我指的是这个:
class UserServiceImpl implements UserService {
@Autowired
UserService service;
// other service methods...
}
我的问题如下:
- 这是如何实现的?
Spring 如何管理这个?它是否将相同的对象分配给自自动连线参考?像这样:
UserServiceImpl serviceImpl = new UserServiceImpl();
serviceImpl.setService(serviceImpl); // Obviously this would be done via Reflection rather than a setter.
或
Spring 是否制作 2 个单独的对象?像这样:
UserServiceImpl obj1 = new UserServiceImpl();
UserServiceImpl obj2 = new UserServiceImpl();
obj1.setService(obj2);
当我们在RestController 中请求时,只给我们obj1 吗?
- Spring 应用程序上下文中有多少个对象副本?
与上一个问题有关,对象的实际副本有多少?
这是一个非常方便的功能,例如跨方法的事务,但我想知道幕后到底发生了什么。
【问题讨论】:
-
只有一份。为什么会很难做到?创建一个实例并使用常规机制(用于字段注入的反射)将依赖关系设置为自身。这并不难,甚至不仅仅是 Spring EJB 和 CDI 可以做到这一点。如果你开始使用构造函数注入,事情就会变得棘手,因为你现在基本上对自己有一个循环依赖。
标签: java spring dependency-injection ioc-container