不能使用JSF注释@ ListenerFor/@ ListenersFor

hak*_*gan 3 annotations listener systemevent jsf-2

JSF注释@ListenerFor不适用于GlassFish或Tomcat.没有错误或警告.它只是不调用方法processEvent().

@ListenersFor({@ListenerFor(systemEventClass=PostConstructApplicationEvent.class), 
public class MySystemEventListener implements SystemEventListener {

   @Override
   public void processEvent(SystemEvent event) throws AbortProcessingException {
      if(event instanceof PostConstructApplicationEvent){
         System.out.println("*********************************************");
         System.out.println("processEvent Method is Called: PostConstructApplicationEvent");
         System.out.println("*********************************************");
      }

      if(event instanceof PreDestroyApplicationEvent){
         System.out.println("*********************************************");
         System.out.println("processEvent Method is Called: PreDestroyApplicationEvent");
         System.out.println("*********************************************");
      }
}

   @Override
   public boolean isListenerForSource(Object o) {
      return (o instanceof Application);
   }

}
Run Code Online (Sandbox Code Playgroud)

有了这个想法?

Bal*_*usC 5

正如它的javadoc告诉你的那样,@ListenerFor它意图被放在一个UIComponentRenderer实现上,而不是放在一个独立的SystemEventListener实现上.对于后者,你需要将其注册为<system-event-listener>faces-config.xml.

例如

<application>
    <system-event-listener>
        <system-event-listener-class>com.example.MySystemEventListener</system-event-listener-class>
        <system-event-class>javax.faces.event.PostConstructApplicationEvent</system-event-class>
        <system-event-class>javax.faces.event.PreDestroyApplicationEvent</system-event-class>
    <system-event-listener>
</application>
Run Code Online (Sandbox Code Playgroud)

对于特定的功能要求,您可能需要考虑使用急切初始化的应用程序作用域bean.这有点简单,不需要一些冗长的XML:

@ManagedBean(eager=true)
@ApplicationScoped
public void App {

    @PostConstruct
    public void init() {
        // ...
    }

    @PreDestroy
    public void destroy() {
        // ...
    }

}
Run Code Online (Sandbox Code Playgroud)