如何更新@Produces @ApplicationScoped的集合? [英] How can I update a collection that is @Produces @ApplicationScoped?
问题描述
我目前正在从Seam的@Factory
注释中迁移.结合@Observer
,我可以做到:
I'm currently migrating away from Seam's @Factory
annotation. Combined with @Observer
, I could do this:
@Factory(value = "optionsList", scope = ScopeType.APPLICATION)
@Observer("entity.modified")
public List<MyBean> produceEntityOptions() {
List l = getEm().createQuery('select e from entity e').getResultList();
Contexts.getApplicationContext().set("optionsList", l);
return l;
}
哪个会缓存可能使用的选项列表,例如<f:selectItems>
(实际计算可能会更复杂).
Which would cache a list of possible options for use in e.g. <f:selectItems>
(the actual computation can be more complicated).
我已将其翻译为与CDI一起使用
I've translated this for use with CDI to
@Produces @Named("optionsList") @ApplicationScoped
public List<MyBean> produceEntityOptions() {
return getEm().createQuery('select e from entity e').getResultList();
}
,但是(当)外部事件信号表明缓存已过时时,这将失去重新创建缓存的能力.我该如何找回?
but this loses the ability to recreate the cache (only) when an external event signals the cache has gone stale. How can I get that back?
推荐答案
这是您可以做的:
@ApplicationScoped
public class MyListProducer {
// the current list
private List<MyBean> listOfBeans;
// resets / reloads/ refreshes list
private void loadList() {
this.listOfBeans = getEm().createQuery('select e from entity e').getResultList();
}
// initialize the list
@PostConstruct
protected void postConstruct() {
loadList();
}
// listen for the stale event - you'll have to create a type (maybe even qualifiers) yourself
private void resetList(@Observes MyCustomListIsStaleEvent evt) {
loadList();
}
// the producer - to ensure that the producer is called after you refresh the list, make the list of scope @Dependent instead of @ApplicationScoped
@Produces @Named("optionsList")
protected List<MyBean> getList() {
return this.listOfBeans;
}
}
实际上,这就是您想要的.但是我不排除可能存在差异的可能性-不太了解Seam.
I think that in effect, this is what you want. But I don't exclude the possibility that there might be differences - don't know Seam very much.
旁注:您应该考虑通过简单的旧同步或通过使以上内容成为有状态会话bean并利用EJB同步机制来同步观察者和生产者方法.
Side note: You should think about synchronizing the observer and the producer methods, either with plain old synchronization or by making the above a stateful session bean and taking advantage of EJB synchronization mechanisms.
这篇关于如何更新@Produces @ApplicationScoped的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!