How to add an object to application scope in Spring

后端 未结 3 1546
长情又很酷
长情又很酷 2021-02-14 10:06

We can set the request attributes using Model or ModelAndView object in Spring.

We can use @SessionAttributes to keep attributes

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-14 10:38

    Basically all that is needed to configure an application scope is to use the ServletContext, and you can do it in Spring as follows:

    public class MyBean implements ServletContextAware {
    
        private ServletContext servletContext;
    
        public void setServletContext(ServletContext servletContext) {
            this.servletContext = servletContext;
        }
    
    }
    

    javax.servlet.ServletContext could be even injected to your bean implementation as follows:

    @Component
    public class MyBean {
    
        @Autowired
        private ServletContext servletContext;
    
        public void myMethod1() {
            servletContext.setAttribute("attr_key","attr_value");
        }
    
        public void myMethod2() {
            Object value = servletContext.getAttribute("attr_key");
            ...
        }
    
    }
    

提交回复
热议问题