如何在Spring中将对象添加到应用程序范围

Cha*_*nya 9 spring scope spring-mvc

我们可以在Spring中使用ModelModelAndView对象设置请求属性.

我们可以使用@SessionAttributes在会话范围内保留属性.

那么如何application在Spring 中将属性放在范围内,spring是否为此提供了任何注释?

Fra*_*eth 12

基本上,配置应用程序范围所需要的只是使用ServletContext,您可以在Spring中执行以下操作:

public class MyBean implements ServletContextAware {

    private ServletContext servletContext;

    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

}
Run Code Online (Sandbox Code Playgroud)

javax.servlet.ServletContext 甚至可以注入你的bean实现,如下所示:

@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");
        ...
    }

}
Run Code Online (Sandbox Code Playgroud)