Spring Bean Scope: Singleton and Prototype

シングルトンsingleton

Only one instance is created and managed in the Spring container. This instance is shared by all requests so we should use this for stateless beans. Singleton scope is the default scope in Spring.

@Service
public class SomeService{
    // DANGER! This property is shared by all requests so one user might use others' password
    private String password;
    public void authByPassword(){
        // ...
    }
}

prototype

A new instance is created by each request for that bean. This should be used when the bean is designed for stateful usage.

@Service
@Scope("prototype")
public class SomeService{
    private String password;
    public void authByPassword(){
        // ...
    }
}

But be cautious about the Controller’s class. If the controller which use the SomeService, is singleton scope, one new instance of the service is injected when and only when the controller is instanced.

1.5.3. プロトタイプ Bean 依存関係を持つシングルトン Bean

Spring の @Scope のデフォルト挙動

comments powered by Disqus