How to lazy init a dependency that 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 classA bean is instantiated, classB bean is also instantiated, despite of @Lazy annotation. How can I avoid classB bean instantiation ?
You can't really do it like that. Like Sotirios said, Spring needs to instantiate it to inject it into ClassA
. You probably can do it manually with the application context. Something like :
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 the getter to access the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With