使用Spring @Lazy和@PostConstruct批注 [英] Using Spring @Lazy and @PostConstruct annotations
问题描述
我有以下课程:
@Repository
class A {
public void method1() {
...
}
}
@Component
class B implements C {
@Autowired
@Lazy
private A a;
public void method2() {
a.method1();
}
}
@Component
class D {
@Autowired
private List<C> c;
@PostConstruct
public void method3() {
// iterate on list c and call method2()
}
}
让我们假设Spring如下初始化bean:
1.创建第一个beanB.创建bean B时,由于@Lazy
批注,字段a
将不会初始化.
2.创建下一个beanD.然后method3()
将被执行,因为它已被@PostConstruct
标记,但是Spring尚未触及beanA.因此,当调用a.method1()时,Spring将创建bean A并将其注入到字段a
中,或者它将抛出NullPointerException
?
Let's suppose Spring initializes the beans as following:
1. First bean B is created. When bean B is being created, field a
will not be initialized because of the @Lazy
annotation.
2. Next bean D is created. Then method3()
will get executed as it is marked with @PostConstruct
, but bean A is not yet touched by Spring. So when a.method1() will be called, then will Spring create bean A and inject it into the field a
or will it throw a NullPointerException
?
推荐答案
您需要了解,将@Lazy
指定为注入的一部分时会发生什么.根据文档:
You need to understand, what's going on when you're specifying @Lazy
as part of injection. According to documentation:
@Lazy
除了其用于组件初始化的作用 注释也可以放在标有的注入点上@Autowired
或@Inject
.在这种情况下,它会导致注入 惰性解析代理.
In addition to its role for component initialization, the
@Lazy
annotation may also be placed on injection points marked with@Autowired
or@Inject
. In this context, it leads to the injection of a lazy-resolution proxy.
这意味着在启动时,Spring将注入代理类的实例而不是类A
的实例.代理类是自动生成的类,具有与类A
相同的接口.第一次调用任何方法时,代理都会在self内创建类A
的实例.之后,所有方法调用将重定向到代理内部的类A
的该实例.
This means that on start Spring will inject instance of proxy class instead of instance of class A
. Proxy class is automatically generated class that have same interface as class A
. On first call of any method proxy will create instance of class A
inside of self. After that all calls of methods will be redirected to this instance of class A
inside of proxy.
因此没有理由担心任何问题.
So there is no reason to be afraid of any problems.
这篇关于使用Spring @Lazy和@PostConstruct批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!