[英]How does bean self-auto-wiring work in Spring?
我最近在 Spring 中发现的一个非常酷且相当令人难以置信的功能是自动装配一个 bean 。
我指的是这个:
class UserServiceImpl implements UserService {
@Autowired
UserService service;
// other service methods...
}
我的问题如下:
Spring 是如何管理这个的? 它是否将相同的 object 分配给自自动接线参考? 像这样:
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
?
与上一个问题相关,object 的实际副本有多少?
对于跨方法事务之类的事情,这是一个非常方便的功能,但我想知道这里的幕后究竟发生了什么。
只有一个副本并使用反射
让我们看看这个样本
@Service
public class SampleService {
@Autowired
private SampleService service;
public SampleService getService() {
return service;
}
}
@SpringBootApplication
public class RestServiceApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context
= SpringApplication.run(RestServiceApplication.class, args);
SampleService sampleService = context.getBean(SampleService.class);
//This will print true
System.out.println(sampleService == sampleService.getService());
}
}
sampleService == sampleService.getService()
为真;如果您使用 @Transactional、@Cachable 等注释,它不会注入 UserServiceImpl。它实际上注入了代理。
但作为基础,它使用相同的实例。
从 4.3 开始,@Autowired 还考虑了用于注入的自引用(即,对当前注入的 bean 的引用)。 请注意,自我注入是一种后备。 对其他组件的常规依赖始终具有优先权。 从这个意义上说,自我引用不参与常规的候选人选择,因此尤其从来不是主要的。 相反,它们总是以最低的优先级结束。 实际上,您应该仅将自引用用作最后的手段(例如,通过 bean 的事务代理调用同一实例上的其他方法)。 在这种情况下,请考虑将受影响的方法分解为单独的委托 bean。 或者,您可以使用 @Resource,它可以通过其唯一名称获得返回到当前 bean 的代理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.