简体   繁体   中英

How to guarantee a bean is instantiated only once by Spring

I would like to know how to tell Spring load a bean which I've defined in a context just once? Is this possible? How is this called and what do I need to do?

I'd basically like to make sure the class is never re-instantiated and that the same instance is re-used.

All beans in spring are singletons by default so they will be instantiated just once. So you have this out of the box and need just to register bean in context by xml or Annotations .

Single instance is the default behavior. Unless you're loading multiple contexts, you should have only one instance.

在xml配置文件中注册bean,我们可以指定bean的范围,但是bean的无效范围是单调的。

您应该避免多次加载applicationContext.xml。

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