2

我想创建一个带有注释的 Faces 应用程序侦听器我有以下类:

package com.chhibi.listener;

    import javax.faces.application.Application;
    import javax.faces.event.AbortProcessingException;
    import javax.faces.event.PostConstructApplicationEvent;
    import javax.faces.event.PreDestroyApplicationEvent;
    import javax.faces.event.SystemEvent;
    import javax.faces.event.SystemEventListener;

    public class FacesAppListener implements SystemEventListener {

        @Override
        public void processEvent(SystemEvent event) throws AbortProcessingException {

            if (event instanceof PostConstructApplicationEvent) {
                // other code here
            }

            if (event instanceof PreDestroyApplicationEvent) {
                //other code here
            }

        }

        @Override
        public boolean isListenerForSource(Object source) {
            // only for Application
            return (source instanceof Application);

        }
    }

我想用faces-config.xml注解替换下面的配置,怎么办?

<!-- Application is started -->
        <system-event-listener>
            <system-event-listener-class>
                com.chhibi.listenner.FacesAppListener
            </system-event-listener-class>
            <system-event-class>
                javax.faces.event.PostConstructApplicationEvent
            </system-event-class>                       
        </system-event-listener>     

        <!-- Before Application is shut down -->
        <system-event-listener>
            <system-event-listener-class>
                com.chhibi.listenner.FacesAppListener
            </system-event-listener-class>
            <system-event-class>
                javax.faces.event.PreDestroyApplicationEvent
            </system-event-class>                       
        </system-event-listener> 
4

1 回答 1

2

没有注释。更重要的是,您实际上使用了错误的工具。只需使用热切初始化的 应用程序范围的 托管 bean

@ManagedBean(eager=true)
@ApplicationScoped
public class MyApplicationBean {

    @PostConstruct
    public void onPostConstruct() {
        // Put code here which should be executed on application's startup.
    }

    @PreDestroy
    public void onPreDestroy() {
        // Put code here which should be executed on application's shutdown.
    }

}

就这样。不需要额外的 XML 冗长。

或者,如果您对可用的 JSF 工件不感兴趣FacesContext,那么您也可以使用标准 servlet 上下文侦听器:

@WebListener
public class MyApplicationListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        // Put code here which should be executed on application's startup.
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // Put code here which should be executed on application's shutdown.
    }

} 

同样在这里,不需要额外的 XML。

SystemEventListener旨在附加到 aUIComponent或 a而Renderer不是独立使用。

于 2013-07-20T01:44:31.763 回答