Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Inject a Bean with EJB 3.1 before the class constructor runs?

I have a Facade that has a persistence unit. And I need the Facade and it's dependencies initialized before the RoleController Conconstructor runs, is it possible in EJB 3.1 to do that ?

In Spring you simple add some parameters (preConstruction="true") to the @configurable and it's done.

But in EJB I cannot find a way to do that I always get a NullPointer...

@FacesConverter("rolesConverter")
@Named("roleController")
@SessionScoped
@TransactionManagement(TransactionManagementType.CONTAINER)
public class RoleController implements Serializable, Converter{

    private List<Roles> listOfRoles; 
    private List<Roles> listChoosenRoles;
    private DualListModel<Roles> listOfDualRoles;
    @EJB
    private RoleFacade roleFacade;

    public RoleController(){
        listOfRoles = roleFacade.getListOfRoles();
        listChoosenRoles = new ArrayList();
        listOfDualRoles = new DualListModel<Roles>(listOfRoles, listChoosenRoles);
    }
like image 753
Cristiano Fontes Avatar asked Oct 07 '11 19:10

Cristiano Fontes


1 Answers

It is generally a bad idea to perform any logic in the constructor (not only on EJB playground). Use @PostConstruct instead:

@PostConstruct
public init(){
    listOfRoles = roleFacade.getListOfRoles();
    listChoosenRoles = new ArrayList();
    listOfDualRoles = new DualListModel<Roles>(listOfRoles, listChoosenRoles);
}

With this annotation the container will first instantiate an EJB object, JVM runs an (empty) constructor, container via reflection injects dependencies and when everything is ready calls all methods annotated with @PostConstruct in unspecified order. Now the EJB is ready to serve requests.

I think some containers/newer EJB spec allows constructor injection, but I have never used it.

like image 163
Tomasz Nurkiewicz Avatar answered Oct 07 '22 01:10

Tomasz Nurkiewicz