Spring Bean上下文中有许多未使用的bean是否会浪费大量资源?

时间:2020-03-06 14:24:09  来源:igfitidea点击:

几个不同的项目正在使用我的模型层,并且无论哪个项目正在使用它,我都希望对模型使用一个XML Spring Configuration文件。

我的问题是:由于不是所有实例都没有使用所有bean,如果没有实例化,我是否在浪费大量资源?我不太确定Spring在加载它们方面有多懒,因为到目前为止这从来都不是问题。

有任何想法吗?

解决方案

默认情况下,Spring bean是单例的,并在创建应用程序上下文时(在启动时)实例化。因此,假设我们没有覆盖默认行为,那么将创建每个Bean的单个实例。

取决于对象。

但是,未使用的代码是"多余的",会增加维护成本。

最好删除引用和类。如果以后需要它们,我们始终可以从版本控制中还原。

摘自Spring参考手册:

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耗尽了文件锁或者数据库连接之类的资源,否则如果我们更容易为多个(但不同)概要文件进行这种配置,那么我就不必担心简单的内存开销。

除了其他注释外:还可以通过使用<beans />元素上的default-lazy-init属性来指定要延迟初始化的整个配置文件;例如:

<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>

如果我们有很多bean,这比向每个bean添加lazy-init属性要容易得多。