问题描述
我有一个ApplicationScoped bean,我想在石英作业实现中访问它.该bean在整个运行时都保存一个哈希图,我想在作业运行时填充该哈希图.但是,FacesContext在工作内部没有上下文.我可以访问ServletContext.是否可以通过ServletContext访问我的bean?
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?
我访问Servlet上下文的代码:
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");
}
我的QuartzServletContext在web.xml中定义为:
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>
推荐答案
是的,它作为属性存储在ServletContext
中.像其他任何属性一样获取它:
Yes, it's stored as an attribute in ServletContext
. Obtain it like any other attribute:
YourApplicationScopedBean bean = servletContext.getAttribute("yourApplicationScopedBeanName");
//use it...
如果bean
为null
,则似乎在开始石英作业时未创建您的bean.通过在其定义中添加eager=true
来确保创建了Bean:
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...
}
}
请注意,eager=true
仅适用于@ApplicationScoped
豆.
如果这仍然不起作用,则似乎在创建Bean并将其存储在应用程序上下文中之前就已经触发了石英作业.最好在ServletContextListener
中而不是在@ApplicationScoped
bean中初始化该资源,并通过另一个组件提供对该资源的访问.
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.
这篇关于通过ServletContext访问ApplicationScoped bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!