开发者

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

开发者 https://www.devze.com 2023-04-11 07:08 出处:网络
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 ?

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();
        list开发者_运维问答ChoosenRoles = new ArrayList();
        listOfDualRoles = new DualListModel<Roles>(listOfRoles, listChoosenRoles);
    }


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号