How to @Inject in a PhaseListener

雨燕双飞 提交于 2019-12-18 04:08:34

问题


I have added a PhaseListener to faces-config.xml:

<lifecycle>
    <phase-listener>com.project.NotificationListener</phase-listener>
</lifecycle>

The class seems to be otherwise correct as it is pretty simple.

public class NotificationListener implements PhaseListener {

    @Inject
    private MyCDIStuff stuff;

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RENDER_RESPONSE;
    }

    @Override
    public void beforePhase(PhaseEvent event) {
        this.stuff.doStuff();
    }
}

The 'beforePhase' method gets called correctly, however the MyCDIStuff object is null. I tried using annotation @Singleton for the class which most likely was incorrect, and it didn't make the injection work either.

Is there a way to inject CDI managed beans in the PhaseListener?


回答1:


Before JSF 2.2, PhaseListeners are not registered as CDI injection targets. Using @Inject (and @EJB) has effectively no effect in PhaseListeners. You'd need to manually grab the CDI managed beans by programmatically evaluating an EL expression referencing the @Named's (implicit) name, or as last resort via JNDI and BeanManager which is quite clumsy.

So, if you can't upgrade to JSF 2.2 (which should be compatible with any JSF 2.0/2.1 and Servlet 3.0 compatible web application), then your best bet is programmatically evaluating an EL expression referencing the @Named name. Assuming that you've a

@Named("stuff")
public class MyCDIStuff {}

then this should do:

FacesContext context = event.getFacesContext();
MyCDIStuff stuff = context.getApplication().evaluateExpressionGet(context, "#{stuff}", MyCDIStuff.class);
// ...



回答2:


If you can't go JSF 2.2 your best bet is to use Deltaspike Core.

It offers MyCDIStuff myCDIStuff = BeanProvider.getContextualReference(MyCDIStuff.class, false);

Deltaspike is how you should get stuff rather then inventing that yourself. For example if you must have the BeanManager (for example to fire an event) then Deltaspike core also offers BeanManagerProvider.

http://deltaspike.apache.org/core.html



来源:https://stackoverflow.com/questions/19930241/how-to-inject-in-a-phaselistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!