如何在Spring中将对象添加到应用程序范围 [英] How to add an object to application scope in Spring

查看:103
本文介绍了如何在Spring中将对象添加到应用程序范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

We can use @SessionAttributes to keep attributes in session scope.

然后我如何在Spring的application范围内放置属性,spring是否为此提供了任何注释?

Then how can I put an attribute in application scope in Spring, does spring has provided any annotation for that?

推荐答案

基本上,配置应用程序作用域所需的全部是使用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");
        ...
    }

}

这篇关于如何在Spring中将对象添加到应用程序范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆