Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy init an injected bean dependency (Spring 3)

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 ?

like image 350
Ana Avatar asked Nov 13 '22 01:11

Ana


1 Answers

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.

like image 161
Jean-Philippe Bond Avatar answered Nov 15 '22 06:11

Jean-Philippe Bond