英文:
How is method injection implemented?
问题
在实现类似Spring的依赖注入过程中,我感到困惑的是Spring是如何通过调用内部方法来注入bean的,但它是如何做到这一点的呢?
我该如何实现这样的IoC容器:
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
B b = new B();
b.setA(a());
return b;
}
@Bean
public C c() {
C c = new C();
c.setB(b());
return c;
}
英文:
During my implementation of spring-like dependency injection, I was puzzled by the fact that spring can injected beans by invoking internal methods, but how did it do this?
How can I implement ioc container like this:
@Bean
public A a() {
return new A();
}
@Bean
public B b() {
B b = new B();
b.setA(a());
return b;
}
@Bean
public C c() {
C c = new C();
c.setB(b());
return c;
}
答案1
得分: 1
假设我们正在讨论 @Configuration
类,动态实例代理被创建(使用CGLIB),然后所有方法调用都会被代理逻辑拦截。
对于单例bean(默认bean范围),实际方法只会在第一次调用时被调用一次 - 这是你可以通过调试器自行验证的。连续的调用会被拦截,并且会从注册表中返回预先存储的实例。
英文:
Assuming we are talking about @Configuration
class, dynamic instance proxy is created (using CGLIB) and than all methods invocations are intercepted by proxy logic.
In case of singleton beans (default bean scope) actual method will be invoked only once on first invocation - this is something you can verify yourself using the debugger. Consecuive calls are intercepted and proped instance is returned from the registry.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论