如何在 Spring Boot 中设置惰性初始化的默认行为?

And*_*ili 5 spring lazy-initialization spring-boot

我正在开发我的第一个Spring Boot应用程序,但遇到以下问题。

我想设置默认所有bean都是延迟加载的。我知道我可以将它添加@Lazy到我所有的@Componentbean 中,但我希望默认所有 bean 都设置为惰性...

Spring Boot 中,我没有 XML 配置文件或配置类,但我只有一个application.properties配置文件。

那么,如何将所有 bean 的默认行为设置为 lazy=true

Per*_*erg 7

要实现BeanFactoryPostProcessor默认设置延迟初始化(如果您在@Configuration类之外动态定义一些 bean,则可能需要这样做),以下方法对我有用:

@Component
public class LazyBeansFactoryPostProcessor implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory( ConfigurableListableBeanFactory beanFactory ) throws BeansException {
        for ( String name : beanFactory.getBeanDefinitionNames() ) {
            beanFactory.getBeanDefinition( name ).setLazyInit( true );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这本质上是将@Lazy注释放在所有 your@Component@Services 上。@Eager如果您走这条路,您可能想发明一种机制来注释类,或者只是在LazyBeansFactoryPostProcessor上面硬连线一个列表。

进一步阅读

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/config/BeanFactoryPostProcessor.html


小智 5

从 spring-boot 2.2.2.RELEASE 版本开始,您可以在 application.properties 文件中使用以下属性

spring.main.lazy-initialization=true
Run Code Online (Sandbox Code Playgroud)

如需进一步阅读和一个很好的例子,请参阅

https://www.baeldung.com/spring-boot-lazy-initialization
https://spring.io/blog/2019/03/14/lazy-initialization-in-spring-boot-2-2
Run Code Online (Sandbox Code Playgroud)