简体   繁体   English

ServletContext 是在 Servlets 之间共享资源的首选方式吗?

[英]Is the ServletContext the preferred way to share resources among Servlets?

When I was looking for ways to share resources (eg a DataSource) between Servlets, most of the time using a ServletContextListener is proposed.当我在寻找在 Servlets 之间共享资源(例如 DataSource)的方法时,大部分时间都建议使用 ServletContextListener。 Is this the standard way for sharing resources?这是共享资源的标准方式吗? Or are there alternatives?或者有其他选择吗?

It depends on your requirement.这取决于您的要求。 You can, however, create a repository, for example a singleton object to keep your resources, of which object just one instance exists in whole JVM. You can, however, create a repository, for example a singleton object to keep your resources, of which object just one instance exists in whole JVM. Moreover, it's not a good practice to use servletcontext to get instances of resources for example data sources because of concurrency issues.此外,由于并发问题,使用 servletcontext 获取资源实例(例如数据源)并不是一个好习惯。 For data resources i would use JNDI resources and let container (tomcat or an application server) manage these resources, like any other service objects for instance DAOs.对于数据资源,我将使用 JNDI 资源并让容器(tomcat 或应用程序服务器)管理这些资源,就像任何其他服务对象(例如 DAO)一样。 Spring solves these problems with an application context in which all service beans live. Spring 通过所有服务 bean 所在的应用程序上下文解决了这些问题。 you need to define your service objects as beans in this context and these can be injected (see dependency injection - CDI) in controllers, interceptors etc. where they are needed with different strategies.您需要在此上下文中将您的服务对象定义为 bean,并且可以在控制器、拦截器等中使用不同的策略将它们注入(参见依赖注入 - CDI)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM