在生产模式下禁用相位监听器

问题描述 投票:0回答:3

我已经设置了一些对我们的应用程序非常有用的东西。 在开发模式中有用,但在生产中没有用。 例如,我注册了这个监听器

<lifecycle>
    <phase-listener>org.primefaces.component.lifecycle.LifecyclePhaseListener</phase-listener>
</lifecycle>

在生产模式下,没有必要这样做,所以我想知道使用JSF应用程序的人如何通过在生产模式下考虑PROJECT_STAGE状态来禁用这些功能?

PS:在xhtml页面中,我知道这很容易,因为我可以通过使用#{facesContext.application.projectStage eq 'Development'}决定不呈现组件

jsf
3个回答
2
投票

您可以通过编程方式注册PhaseListener,而不是通过faces-config.xml进行注册,例如:

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

    @PostConstruct
    private void initialize() {
        LifecycleFactory factory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
        Lifecycle lifecycle = factory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
        if (ProjectStage.Development.equals(getProjectStage())) {
            lifecycle.addPhaseListener(new PhaseListenerImpl());
        }
    }

    private ProjectStage getProjectStage() {
        FacesContext fc = FacesContext.getCurrentInstance();
        Application appl = fc.getApplication();
        return appl.getProjectStage();
    }
}

(请参阅http://javaevangelist.blogspot.de/2012/05/jsf-2-tip-of-day-programmatic.html


1
投票

使用系统事件侦听器(请参见https://www.tutorialspoint.com/jsf/jsf_applicationevents_tag.htm ):

public class PostConstructApplicationListener implements SystemEventListener {

    @Override
    public void processEvent(SystemEvent event) {
        if (event instanceof PostConstructApplicationEvent) {
            setupLifeCycleListener();
        }
    }

    /**
     * Add <code>org.primefaces.component.lifecycle.LifecyclePhaseListener</code> in case PROJECT_STAGE is not set to "Production"
     */
    private void setupLifeCycleListener() {
        if (Faces.getApplication().getProjectStage() != ProjectStage.Production) {
            LifecycleFactory factory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
            Lifecycle lifecycle = factory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
            lifecycle.addPhaseListener(new LifecyclePhaseListener());
        }
    }

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

0
投票

您可以通过扩展Primefaces LifecyclePhaseListener并在未处于开发模式的情况下从getPhaseId()方法返回nullgetPhaseId()

public class LifecycleForDevelopmentPhaseListener extends LifecyclePhaseListener {
    @Override
    public PhaseId getPhaseId() {
        if (!FacesContext.getCurrentInstance().isProjectStage(ProjectStage.Development)) {
            return null;
        }
        return super.getPhaseId();
    }

}

这将绕过相位监听器

© www.soinside.com 2019 - 2024. All rights reserved.