Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add an object to application scope in Spring

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

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

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

like image 255
Chaitanya Avatar asked Aug 15 '15 15:08

Chaitanya


2 Answers

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

}
like image 161
Francisco Spaeth Avatar answered Oct 19 '22 03:10

Francisco Spaeth


When you mention about storing your model at application scope then I would conclude you wish to store it at the ServletContext level. For doing that you need to make your controller implements ServletContextAware interface.

import org.springframework.web.context.ServletContextAware;

// ...

public class MyController implements ServletContextAware {

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

After getting access to ServletContext you can add it as a attribute

servletContext.setAttribute("modelKey", modelObject);

Kindly let me know if this is what you are looking for.

like image 2
Mudassar Avatar answered Oct 19 '22 02:10

Mudassar