I have following classes:
@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()
}
}
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
?
You need to understand, what's going on when you're specifying
@Lazy
as part of injection. According to documentation: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 classA
. On first call of any method proxy will create instance of classA
inside of self. After that all calls of methods will be redirected to this instance of classA
inside of proxy.So there is no reason to be afraid of any problems.