Prashant Bhate
Prashant Bhate

Reputation: 11087

Spring framework default-lazy-init all beans

Is there a spring property to lazy-init all beans that spring framework loads ?

I know about these properties

 - lazy-init="true"
 - default-lazy-init="true"

however there are multiple spring config xml files and some are packaged within jar so dont have liberty to change neither <bean> nor <beans> tag.

Any other way to tackle this via configuration ? or programatically ?

Upvotes: 6

Views: 5596

Answers (5)

Gonen I
Gonen I

Reputation: 6107

Starting with Spring Boot 2 you can use the spring.main.lazy-initialization property to configure lazy initialization across the whole application.

Setting the property value to true means that all the beans in the application will use lazy initialization.

in application.yaml

spring:
  main:
    lazy-initialization: true

or in application.properties

spring.main.lazy-initialization=true

Upvotes: 0

I've implemented this on my company, had to extend some classes of spring tough. It wasn't easy, but we gained about 20s on every tomcat startup. Unfortunately, for privacy clauses, I can't show the code, but take a look at ClassPathBeanDefinitionScanner,DefaultBeanDefinitionDocumentReader,ContextNamespaceHandler and ComponentScanBeanDefinitionParser classes.

Upvotes: 0

maryoush
maryoush

Reputation: 173

According to java doc this should work ( though it looks not nice)

if (context.getBeanFactory() instanceof DefaultListableBeanFactory)
    {
        ((DefaultListableBeanFactory) context.getBeanFactory()).setAllowEagerClassLoading(false);
    }

Upvotes: 0

danny.lesnik
danny.lesnik

Reputation: 18639

You caN also use @Lazy annotation, but it is the same as you mentioned above.

Upvotes: 2

Andrew White
Andrew White

Reputation: 53496

Short of extending the Spring bean loader, none that I know of.

Upvotes: 2

Related Questions