Lazy initializes an injected bean dependency (Spring 3)

How to lazy initialize a dependency, which is @Inject?

public class ClassA { @Inject ClassB classB; } @Configuration public class Config { @Bean public ClassA classA() { return new ClassA(); } @Bean @Lazy public ClassB classB() { return new ClassB(); } } 

When you create an instance of classA bean, an instance of class B bean is also created, despite the @Lazy annotation. How can I avoid instantiating a bean class?

+4
source share
1 answer

You cannot do it like that. As Sotirios said, Spring must create an instance to inject it into ClassA . You can probably do this manually using the application context. Sort of:

 public class ClassA { @Inject private ApplicationContext appContext; private ClassB classB; //Bean will be instanciated when this method is called public ClassB getClassB() { if (classB == null) { classB = appContext.getBean(ClassB.class); } return classB; } } 

And then use getter to access the object.

0
source

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


All Articles