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

1

6

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);
    }
Latta answered 7/10, 2011 at 19:51 Comment(0)
E
11

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.

Erde answered 7/10, 2011 at 19:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.