gpt4 book ai didi

java - Spring Bean Context 中有许多未使用的 bean 会浪费大量资源吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:54 26 4
gpt4 key购买 nike

我的模型层被几个不同的项目使用,我想为模型使用单个 XML Spring 配置文件,而不管哪个项目正在使用它。

我的问题是:由于并非所有项目都使用了所有 bean,如果没有实例化,我是否会浪费大量资源?我不太确定 Spring 在加载它们方面有多懒惰,因为直到现在它才成为问题。

有什么想法吗?

最佳答案

取自Spring Reference Manual :

The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup. Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process. Generally this is a good thing, because it means that any errors in the configuration or in the surrounding environment will be discovered immediately (as opposed to possibly hours or even days down the line).

However, there are times when this behavior is not what is wanted. If you do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested.

When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the [bean element] ; for example:

<bean id="lazy" class="com.foo.ExpensiveToCreateBean" lazy-init="true"/>

但是,除非您的 bean 耗尽了文件锁或数据库连接等资源,否则如果您可以更轻松地为多个(但不同的)配置文件配置一个配置,我就不会太担心简单的内存开销。

关于java - Spring Bean Context 中有许多未使用的 bean 会浪费大量资源吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/98320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com