Using Spring @Lazy and @PostConstruct annotations

9k views Asked by At

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?

1

There are 1 answers

1
Ken Bekov On BEST ANSWER

You need to understand, what's going on when you're specifying @Lazy as part of injection. According to documentation:

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.

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.