3

I want to inject a @SessionScoped and a @RequestScoped beans into my PhaseListener implementation, but I got NullPointerException.

I use tomcat with weld implementation to achieve CDI. I started to migrate JSF 2.2 to 2.3, so I changed to CDI from FacesContext. Well I replaced @ManagedBean to @Named and any other things to must do during migration like: - add beans XML to every modules - add BeanManager to context XML - delete bean declarations from faces-config.xml - add SPI BeanManager as resource-env-ref to web.xml How can I inject any bean to PhaseListener implementations?

@Named
@SessionScoped
public class MyHandler implements Serializable {    
..}

@Named
@RequestScoped
public class MyController extends MyParentController<Example> {
..}

public class MyPhaseListener implements PhaseListener {

private MyHandler myHandler;
private MyController myController;

@Inject
public void setMyHandler(MyHandler myHandler) {
    this.myHandler= myHandler;
}

@Inject
public void setMyController (MyController myController) {
    this.myController= myController;
}
...

public void afterPhase(PhaseEvent event) {
myHandler.method()
}

myHandler injected bean is null in afterPhase method.

sophros
  • 14,672
  • 11
  • 46
  • 75
BravoNine
  • 101
  • 2
  • 9
  • I think that it is not a duplicated question. I asked about the injection in JSF 2.3, not in JSF 2.2. My goal is to eliminate all code what getting bean from context via EL expression. – BravoNine Jan 31 '19 at 14:34
  • Did you try field injection? – Kukeltje Jan 31 '19 at 19:04
  • In https://stackoverflow.com/questions/19930241/how-to-inject-in-a-phaselistener BalusC suggests it should work as of JSF 2.2, but i've been unable to `@Inject` something into a Phaselistener using fieldinjection either (using openWebbeans, Mojarra 2.3, CDI API 2.0). Revoked my duplication flag and am interested in the solution. Upvoted therefore. – Selaron Jan 31 '19 at 19:14
  • 1
    @BravoNine Best to put your answer into a response, and mark it as accepted to help others ;) – Steven De Groote Feb 04 '19 at 11:04

2 Answers2

1
  1. I put CDI configuration file beans.xml into folder META-INF instead of WEB-INF
  2. In beans.xml I had to change bean-discovery-mode from "annotated" to "all".
  3. I forgot to add a class with @FacesConfig(version = Version.JSF_2_3) annotation( to enable EL resolution for CDI beans).
  4. Also forgot to change faces-config.xml version to 2.3
Martin Höller
  • 2,714
  • 26
  • 44
erickdeoliveiraleal
  • 708
  • 2
  • 9
  • 21
0

Fortunately I solved the problem... A few things I had to do:

  1. I put beans.xml into META-INF/, but beans.xml has to be under WEB-INF.
  2. In beans.xml I had to change bean-discovery-mode from "annotated" to "all".
  3. I forgot to add a class with @FacesConfig(version = Version.JSF_2_3) annotation( to enable EL resolution for CDI beans).
  4. Also forgot to change faces-config.xml version to 2.3.
BravoNine
  • 101
  • 2
  • 9