【问题标题】:How can I update a collection that is @Produces @ApplicationScoped?如何更新 @Produces @ApplicationScoped 的集合?
【发布时间】:2013-09-17 09:58:55
【问题描述】:

我目前正在远离 Seam 的 @Factory 注释。结合@Observer,我可以这样做:

@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;
}

这将缓存一个可能的选项列表以用于例如&lt;f:selectItems&gt;(实际计算可能更复杂)。

我已将其翻译为与 CDI 一起使用

@Produces @Named("optionsList") @ApplicationScoped
public List<MyBean> produceEntityOptions() {
    return getEm().createQuery('select e from entity e').getResultList();
}

但这会失去重新创建缓存的能力(仅)当外部事件表明缓存已过时。我怎样才能把它拿回来?

【问题讨论】:

    标签: jsf-2 cdi


    【解决方案1】:

    你可以这样做:

    @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。

    旁注:您应该考虑同步观察者和生产者方法,或者使用普通的旧同步,或者通过将上述设置为有状态会话 bean 并利用 EJB 同步机制。

    【讨论】:

    • 这就是我所担心的。我将尝试将其扩展到数十个列表并在此之后接受。
    • 同步提示也是 +1。这是我在这种情况下没有想到的领域。
    • @mabi 可以肯定,在最坏的情况下,列表的数量将是您触发 MyCustomListIsStaleEvent + 1 的次数。也就是说,如果您将列表注入到请求和会话范围内豆子,真的不会那么多。
    • 不,我的 JSF 模板中使用了不止一个 @Factory/@Produces。我必须为每个方法创建 @Observes@Produces 方法,如果我能节省时间将选项列表绑定到像 #{optionProvider.industryCodes} 这样的 bean 并且只担心 @Observes 事件,这让我很难思考。跨度>
    猜你喜欢
    • 1970-01-01
    • 2015-05-10
    • 2011-04-27
    • 2022-12-07
    • 2014-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多