@Scope - JiyangM/spring GitHub Wiki

Spring支持不同的scope。不同scope在使用上是有差异的,比如singleton与prototype。

  • singleton spring默认采用的scope,在Spring的IoC容器中只存在一个对象实例,所有该对象的引用都共享这个实例。该实例从容器启动,并因为第一次被请求而初始化之后,将一直存活到容器退出,也就是说,它与IoC容器“几乎”拥有相同的“寿命”。

  • prototype 容器每次返回给请求方一个新的实例对象后,就任由这个对象“自生自灭”了。

注意: 当一个prototype的bean A 被singleton B的引用时,实际上使用的是同一个实例A。

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        return new RabbitTemplate(connectionFactory);
    }
@Service
@Slf4j
public class TransferDebtService {
 @Autowired
    private RabbitTemplate rabbitTemplate;
}

上面的代码PROTOTYPE就不会起作用。

参考: https://waylau.com/spring-singleton-beans-with-prototype-bean-dependencies/