Spring bean lazy initialization

I was thinking about lazy beans initialization in Spring. It was not entirely clear to me that the โ€œlazy" here means that the bean will be created when it is referenced.

I was expecting lazy initialization support in Spring to be different. I thought this was a lazy method-based creature. I mean, every time the method is called, it will be created.

I think that this can be easily solved by creating a proxy instance of a specific bean and initializing with any method call.

I missed something, why is this not implemented? Are there any problems with this concept?

Any feedback / idea / answer will be appreciated.

Thanks guys!

+5
source share
2 answers

You can achieve the desired behavior by pointing the bean to proxyMode ScopedProxyMode.TARGET_CLASS (CGLIB) or ScopedProxyMode.INTERFACES (JDK).

for instance

 public class StackOverflow { public static void main(String[] args) { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Conf.class); Bar bar = ctx.getBean(Bar.class); System.out.println(bar); System.out.println(bar.foo.toString()); } } @Configuration class Conf { @Bean @Lazy @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) public Foo foo() { System.out.println("heyy"); return new Foo(); } @Bean public Bar bar() { return new Bar(); } } class Bar { @Autowired public Foo foo; } class Foo { } 

will print

 com.example.Bar@3a52dba3 heyy com.example.Foo@7bedc48a 

demonstrating that the Foo bean was initialized using the @Bean factory method only after calling the method in the Foo instance introduced by the Spring context in the Bar bean.

The @Scope annotation @Scope also be used in a class declaration.

+3
source

Following are my views:

Bean types in Spring Container:

There are two types of Scope beans in a Spring Container . One of them is a prototype , this type of bean will not exist the concept of lazy-init , because these beans will be created when clients will refer to the getBean () method every time . Another Singleton , these bean will be created once , these beans can be lazily instantiated ( just created when they are used, for example @Autowired, refrenced), if you define a bean to use @Lazy or lazy-init = true .

How to implement lazy-init :

Yes, the general implementation is Proxy mode . Spring use JDK Dynamic Proxy and Cglib to implement Proxy , you can learn more about these technologies.

Hope to help you.

-1
source

Source: https://habr.com/ru/post/1247786/


All Articles