Using Spring @Lazy and @PostConstruct annotations

左心房为你撑大大i 提交于 2019-12-11 03:09:02

问题


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:


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.



来源:https://stackoverflow.com/questions/41443300/using-spring-lazy-and-postconstruct-annotations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!