我可以创建带注释的Faces应用程序监听器类吗?

时间:2013-07-20 01:22:41

标签: java jsf jsf-2 java-ee-6

我想创建一个带注释的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> 

1 个答案:

答案 0 :(得分:2)

没有注释。更重要的是,你实际上是在使用错误的工具。只需使用eagerly initialized application scoped managed 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冗长。

或者,如果您对FacesContext提供的JSF工件不感兴趣,那么您也可以使用标准的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有意附加到UIComponentRenderer,不能单独使用。