How to insert a Bean with EJB 3.1 before starting the class constructor?

I have a Facade that has a persistence unit. And I need the facade and its dependencies initialized before the Conconstructor RoleController starts, is this possible in EJB 3.1?

In Spring, you simply add some parameters (preConstruction = "true") to @configurable and execute.

But in EJB I can't find a way to do this, I always get 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); } 
+6
source share
1 answer

As a rule, it is a bad idea to execute any logic in the constructor (not only on the EJB playground). Use @PostConstruct :

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

Using this annotation, the container first creates an instance of the EJB object, the JVM starts the (empty) constructor, the container enters dependencies through reflection, and when everything is ready, it will call all methods annotated with @PostConstruct in the unspecified order. EJB is now ready to serve requests.

I think some containers / new EJB specifications allow constructor injection, but I never used it.

+11
source

Source: https://habr.com/ru/post/898863/


All Articles