如何在Spring中将对象添加到应用程序范围 [英] How to add an object to application scope in Spring
问题描述
我们可以在Spring中使用Model
或ModelAndView
对象设置请求属性.
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屋!