applicationServlet实际上如何管理上下文变量?

时间:2017-01-05 09:16:47

标签: java scope local-variables

applicationServlet实际上如何管理上下文变量?如果我在applicationContext级别设置变量,无论它是存储在方法区域还是堆栈区域或堆中, 如果是这样,它如何存储以及如何存储?

这里我创建了局部变量作为MAP并将一些值放在applicationContext级别。

我在这里写了一些示例代码。

    public class ContextLoaderListener implements ServletContextListener {
    private ServletContext ctx;
    private WebApplicationContext springContext;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
    Map<String, String> resourceMap=new HashMap<>();
    resourceMap.put("1","abc1");
    resourceMap.put("2","abc2");
    resourceMap.put("3","abc3");
    sce.getServletContext().setAttribute("resourceMap", resourceMap);
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) { }
    }

1 个答案:

答案 0 :(得分:2)

我将在此回答您的评论,我认为它也会回答您的问题。

您在评论中提出的问题如下:

  

resourceMap是此partcular方法的本地映射。完成后   执行此方法的resourceMap局部变量即将执行   破坏。如果是,那么resourceMap上下文变量如何引用本地   变量resourceMap?

井资源地图只是一个本地参考。对象本身在堆中。在方法执行完成后,resourceMap会丢失,这是对的。但是,您将引用的副本传递给另一个寿命更长的对象。请参阅以下示例:

class TestClass {
    public static void main(String[] args) {
        final ServletContext servletContext = new ServletContext();
        final ServletContextEvent servletContextEvent = new ServletContextEvent(servletContext);
        final ServletContextListener servletContextListener = new ServletContextListener();
        servletContextListener.contextInitialized(servletContextEvent);
        final Object resourceMap = servletContext.getMap().get("resourceMap");
        // See, resourceMap is still accesiable. Because it still has an alive reference to it from ServletContext!
        System.out.println(resourceMap);
        // Output will be:
        // {1=abc1}
    }
}

class ServletContext {

    final Map<String, Object> map = new HashMap<String, Object>();

    public void setAttribute(String resourceMap, Map<String, String> value) {
        this.map.put(resourceMap, value);
    }

    public Map<String, Object> getMap() {
        return map;
    }
}

class ServletContextEvent {
    private final ServletContext servletContext;

    public ServletContextEvent(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    public ServletContext getServletContext() {
        return servletContext;
    }
}

class ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        Map<String, String> resourceMap = new HashMap<String, String>();
        resourceMap.put("1", "abc1");
        sce.getServletContext().setAttribute("resourceMap", resourceMap);
    }
}

这会回答你的问题吗?