Search code examples
javajsf-2dependency-injectionjavabeanscdi

Injecting Beans in JSF 2.0


I have a Session scoped bean

import javax.faces.bean.SessionScoped;
import javax.inject.Named;
@Named
@SessionScoped
public class SessionBean implements Serializable{

I inyect the object in one Filter...

public class FiltroSeguridad implements Filter{

@Inject
private SessionBean sessionBean;

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  HttpServletRequest httpRequest = (HttpServletRequest) request;
  sessionBean.setRutaRedirect(httpRequest.getRequestURI());
}
}

But, I inyect SessionBean in the next interaction...

@Model
public class CuentaUsuarioWebBean implements Serializable{
 @Inject
 private SessionBean sessionBean;

public void loginUsuario() throws IOException{
   sessionBean.getRutaRedirect();
}

}

But the property getRutaRedirect() returns null

I change the import by CDI annotations it still doesn't work (javax.enterprise.context.SessionScoped), same with JSF annotation (javax.faces.bean.ManagedBean and @ManagedProperty).

Thanks.

PD: Sorry for my English!


Solution

  • You can't mix annotations from those two packages you're using javax.faces.bean.SessionScoped for JSF, and import javax.inject.Named for CDI. Both reflect different injection mechanisms and cannot be mixed on the same bean. You have to pick both annotations(for Injection and Bean Scoping) from the same package. Use the following sets from their corresponding packages

    For CDI-based bean definitions

    javax.enterprise.context.SessionScoped //for bean scoping
    javax.inject.Named //for bean declaration
    javax.inject.Inject //for injection
    

    For JSF-based bean definitions

    javax.faces.bean.SessionScoped //for bean scoping
    javax.faces.bean.ManagedBean //for bean declaration
    javax.faces.bean.ManagedProperty //for bean injection
    

    EDIT: Now I understand your requirements better, use the following construct to inject a JSF managed bean

     @ManagedProperty(value="#{yourBeanName}")
     SessionBean yourSessionBean;
    

    Also note that within JSF, you can inject only beans of a wider scope than their targets e.g. you can inject a @SessionScoped bean into a @RequestScoped bean and not the other way around

    But since JSF managed beans are deprecated, better to use the CDI managed ones. In that case you can inject shorter scoped beans in wider scoped ones