且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-02 23:06:10

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

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甚至可以按如下方式注入到您的bean实现中:

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

}