"@inject"-ed attribute remains null

martijnve picture martijnve · Apr 14, 2011 · Viewed 21.3k times · Source

I am trying to inject a service into my bean but it is always null. I get the following error: WELD-001000 Error resolving property userBean against base null.

Some code snippets:

index.xhtml

<h:body>
    Hello from Facelets
    #{userBean.name}
</h:body>

userbean.java

package beans;

import Domain.User;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import service.UserService;

@Named
@SessionScoped
public class UserBean implements Serializable{
    @Inject UserService service;
    private User user;

    public UserBean(){
        this.user = service.find_user("foo");
    }

    public String getName(){
        return "bar";
    }
}

UserService.java

package service;

import Domain.User;
import javax.ejb.Stateless;
import javax.inject.Named;

@Named
@Stateless
public class UserService {
    public UserService(){}

    public User find_user(String name){
        return new User();
    }
}

Answer

Gere picture Gere · Oct 24, 2014

Another alternative is use @PostConstruct method annotation.

@SessionScoped
public class UserBean implements Serializable {
    @Inject UserService service;
    private User user;
    public UserBean() {

    }

   @PostConstruct
    void init(){
        this.user = service.findUser("kaas"); 
    }

  }

Read docs