A singleton bean global has only one shared instance. In the case of a singleton bean as a dependency, the container return will be the same instance.

In other words, when the developer defines the scope of a bean as a singleton, the Swoft IOC container will only create a unique instance of the bean based on the bean definition. These unique instances are cached in the container, and subsequent requests and references to singleton beans will get this unique instance from this cache.


singleton bean is initialized 启动时 framework 启动时 and will only be initialized once. It is not safe to write to a singleton bean . If you read and write a singleton bean at the same time, the context switch will cause the bean data to be inconsistent. This is often caused by business crossover. .

pay attention

singleton generally used for 只读 , not as a way to share memory.

For example, swoft 's config bean is a global singleton. It is only used for reading and will not change during the run. The system throws an exception for the config write operation.


<?php declare(strict_types=1);

namespace Swoft\Config;

use Swoft\Bean\Annotation\Mapping\Bean;

 * Class Config
 * @Bean("config")
 * @since 2.0
class Config

The default is that the score is a global 单例 . To create a singleton bean , you don't have to specify the score .


A bean type singleton will only be destroyed if the 主进程关闭 .