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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top