简体   繁体   中英

how to avoid dependent object creation in spring DI?

I have Class A,B and C. A have ref of B and B have ref of C. A<-B<-C. Assume that we are using spring to injecting object at runtime. When we will call getBean("A") then spring will create object for all depended classes. Now my requirement is to tell spring that it should not create object of class C while A object created. C should create only when calling the B or when flow comes to B.

You will want to explicitly mark your beans as lazy initialized.

   <!-- A bean definition with lazy init set on -->
   <bean id="..." class="..." lazy-init="true">
       <!-- collaborators and configuration for this bean go here -->
   </bean>

The container will not initialize the bean unless required. Please note that if a bean is loaded, it will also load its dependent beans regardless of the value of lazy-init.

By default spring container will initialize all the spring beans declared in you code. If you do not want this behavior then such beans can be configured to be initialized lazily. In your case, If you define bean C to be lazily initialized, it will be initialized when you initialize bean A ( since C is dependent on A) instead of getting initialized when the container/application context/bean factory starts. I think for the behavior you mentioned, there is no such way to define such an initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM