问题
I have an ApplicationScoped bean that I'd like to access in a quartz job implementation. That bean holds a hashmap through run-time and I'd like to populate the hashmap when the job runs. However, the FacesContext is out of context inside the job. I have access to the ServletContext. Is it possible to access my bean through the ServletContext?
My code to access the Servlet Context:
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
SchedulerContext schedulerContext=null;
try {
schedulerContext=context.getScheduler().getContext();
}
catch (SchedulerException e) {
e.printStackTrace();
}
ServletContext servletContext=(ServletContext)schedulerContext.get("QuartzServletContext");
BOCacheM bOCacheM = (BOCacheM) servletContext.getAttribute("bOCacheM");
}
My QuartzServletContext is defined in web.xml as:
<context-param>
<param-name>quartz:scheduler-context-servlet-context-key</param-name>
<param-value>QuartzServletContext</param-value>
</context-param>
<listener>
<listener-class>
org.quartz.ee.servlet.QuartzInitializerListener
</listener-class>
</listener>
回答1:
Yes, it's stored as an attribute in ServletContext
. Obtain it like any other attribute:
YourApplicationScopedBean bean = servletContext.getAttribute("yourApplicationScopedBeanName");
//use it...
If bean
is null
then looks like your bean wasn't created when the quartz job started. Make sure the bean is created by adding eager=true
to its definition:
@ManagedBean(eager=true)
@ApplicationScoped
public class YourApplicationScopedBean {
//...
@PostConstruct
public void init() {
//initialize your shared resources here...
}
}
Note that eager=true
only applies for @ApplicationScoped
beans.
If this still doesn't work, seems like your quartz job is being fired even before the bean is created and stored in the application context. It would be better to initialize this resource in the ServletContextListener
rather than in an @ApplicationScoped
bean and provide access to this resource through another component.
来源:https://stackoverflow.com/questions/28154597/access-applicationscoped-bean-through-servletcontext