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


问题内容

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

我们可以@SessionAttributes用来将属性保留在会话范围内。

那么我怎样才能application在Spring的范围内放置一个属性,spring是否为此提供了任何注释?


问题答案:

基本上,配置应用程序作用域所需的全部就是使用ServletContext,您可以在Spring中按如下所示进行操作:

public class MyBean implements ServletContextAware {

    private ServletContext servletContext;

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

}

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

}