【问题标题】:Which @Scope should I choose for a stateful(?) @Service我应该为有状态(?)@Service 选择哪个 @Scope
【发布时间】:2015-02-07 08:52:40
【问题描述】:

我是 Spring 新手。

我正在开发一个依赖于spring-context 的库项目。

@Scope(value = "@@?")
@Service
public class MyService {

    @PostConstruct private void constructed() {
    }

    @PreDestroying private void destroying() {
        resource.clear();
    }

    public void doSome() throws IOException {
        // try{}finally{} is not the case
        resource = getSome();
        doSome(resource); // may throw an IOException
        resource.clear();
    }

    private transient MyResource resource;
}

我想在每次这个实例被销毁时释放resource

根据@Scope,我可以选择四个选项。

我发现 WebApplicationContext 在我的依赖关系树中不可用。 (我不依赖spring-webmvc

我打算选择ConfigurableBeanFactory.SCOPE_PROTOTYPE

我选择的范围是否会使 MyService 安全?我的意思是任何两个或多个客户端都不能注入同一个服务实例? Spring 容器会处理它吗?

【问题讨论】:

    标签: spring scope


    【解决方案1】:

    确实,RequestSessionGlobal-sessionApplication 范围仅在 Web 感知应用程序上下文中可用。

    Singleton(单个实例每个 Spring 容器)是 Spring 使用的默认范围,因此使用原型范围将保证新实例将被创建并返回给客户端,所以是的 @987654326 @ 是你在这种情况下需要的。

    【讨论】:

      猜你喜欢
      • 2013-01-22
      • 1970-01-01
      • 2019-01-15
      • 2014-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 2019-07-21
      相关资源
      最近更新 更多