Java – how to inject beans using EJB 3.1 before the class constructor runs?

I have a facade with persistence units I need the facade and initialize its dependencies before the rolecontroller constructor runs. Can I do this in EJB 3.1?

In spring, you only need to add some parameters (preconstruction = "true") to @ configurable

But I can't find a method in EJB. 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);
    }

Solution

It is often a bad idea to perform any logic in constructors (not just on EJB operators) Use @ postconstruct instead:

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

Using this annotation, the container will first instantiate the EJB object, the JVM will run the (empty) constructor, inject the dependency container through reflection, and call all methods annotated with @ postconstruct in unspecified order when everything is ready The EJB is now ready to service the request

I think some container / updated EJB specifications allow constructor injection, but I never use it

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>