Question

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 ?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top