How to @Inject in a PhaseListener

前端 未结 2 869
既然无缘
既然无缘 2020-12-16 20:50

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


    com.project.NotificationListener

        
相关标签:
2条回答
  • 2020-12-16 21:06

    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);
    // ...
    
    0 讨论(0)
  • 2020-12-16 21:09

    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

    0 讨论(0)
提交回复
热议问题