在不同的模块中使用相同的Singleton实例

时间:2014-12-11 18:09:37

标签: java singleton jetty

我正在开发一个将在Jetty服务器上运行的Web应用程序。我希望能够将一个对象放入Application本身的hashmap中,然后使用Client回读同一个Object。我在应用程序和客户端中创建了一个HashMap的Singleton实例,认为它是同一个实例,但是在将两个对象打印到控制台后,我发现它们是两个独立的实例,因此不包含相同的数据。有谁知道如何从应用程序和客户端访问HashMap?看看这篇文章,Singleton is not really a singleton我看到我应该使用org.eclipse.jetty.webapp.WebAppContext设置父加载器,但我不确定如何处理它。这是我到目前为止所拥有的。

服务器:

public static void main(String[] args) throws Exception {
    Server server = new Server(8888);
    ServletHandler handler = new ServletHandler();
    handler.addServletWithMapping(App.class, "/S3Mock");//Set the servlet to run.
    server.setHandler(handler);
    server.start();
    server.join();
}

应用:

@SuppressWarnings("serial")
public class App extends HttpServlet  {
@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        S3Controller s3cont = new S3Controller();
        Map appMap = Storage.getInstance();
        s3cont.putObject(appMap, "aws.amazon.com/buckets/mybucket", new Object());
        s3cont.putObject(appMap, "aws.amazon.com/buckets/mybucket2", new Object());
        response.setContentType("text/html");
        response.setStatus(HttpServletResponse.SC_OK);
        response.getWriter().println("<h2>AWS S3</h2>");
    }
}

客户端:

public static void main(String[] args) {
    Client client = Client.create();
    //Get
    WebResource webResource = client.resource("http://localhost:8888/S3Mock");
    ClientResponse response = webResource.accept(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON)
            .get(ClientResponse.class);
    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "
                + response.getStatus());
    }
    S3Controller s3cont = new S3Controller();
    Map m = Storage.getInstance();
    Object b = s3cont.getObject(m, "aws.amazon.com/buckets/mybucket2");
    if(b != null)
        System.out.println(b.toString());
    else
        System.out.println("Object not found");
}

存储

public class Storage {

    private static Map<String, Object> theMap = new HashMap<String, Object>();

    private Storage() {}

    public static Map getInstance() {
        return theMap;
    }
}

启动Jetty服务器后,当我运行客户端时,控制台会读取Object not found,告诉我实际上有两个单独的HashMap实例。

0 个答案:

没有答案