2012-09-21 54 views
0

我目前正在建设使用泽西嵌入码头一个简单的REST接口。从一个HashMap共享的HashMap在码头

Server server = new Server(8080); 
ContextHandlerCollection contexts = new ContextHandlerCollection(); 
ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS); 
ServletHolder sh = new ServletHolder(ServletContainer.class); 
servletContextHandler.addServlet(sh, "/*"); 
server.setHandler(servletContextHandler); 
sh.setInitParameter("com.sun.jersey.config.property.packages", "my.package.containing.jersey.resource"); 

在我的资源,我定义@GET, @PUT, @DELETE方法,这都得到/ PUT /删除对象。

当前我在我的资源类中将HashMap定义为静态ConcurrentHashMap,迄今为止工作良好。

public class MyResource { 

private static final Map<String, MyObjects> myRepository = new ConcurrentHashMap<String, MyObjects>(); 

@GET 
... 

@PUT 
... 

} 

不过,我打算让HashMap访问潜在的其他资源和servlet。
因此,希望将其添加到更广泛的范围应用程序上下文中。
虽然不知道,这可以做得最好吗?
理想地以编程方式。
(我见过有一个在jetty.webapp一个WebAppContext,不知道这是虽然要走的路)。

+0

什么数据库? – sp00m

+0

不,我不需要持久性。 – Will

回答

1

使用一些依赖注入在应用程序中(春,吉斯)中的所有资源需要访问注入HashMap中的一个实例/修改。

+0

感谢您的建议,但我不想添加额外的框架,仅仅是为了扩大一个资源的可访问性。 – Will

+1

然后做没有DI或框架,回辛格尔顿:私有静态最后myRepository = MyHashmap.getInstance()无论你需要它。 –

+0

谢谢,那会做现在。然而,不是我的首选解决方案,因为我不希望所有类都能够获得HashMap,但将范围限制为所有Servlet。如果可能的话,我仍然在寻找将其添加到某个服务器上下文的解决方案。 – Will